views:

144

answers:

1

I have written some custom code that make changes to some of the methods in ActionView::Helpers::AssetTagHelper An example:

module ActionView
  module Helpers
    module AssetTagHelper
      alias old_existing_method existing_method

      def existing_method
        puts "Does foobar"
        return old_existing_method
      end
    end
  end
end

Now normally i would keep this code code in RAILS_ROOT/config/initializers/asset_helper_overrides.rb This works as expected.

Now i want to turn this into a plugin.

I copied this file to the plugin location and the i would require it in init.rb file. However, this doesn't seem to work. I'm not sure why this doesn't work.

I'm guessing maybe its because the file is required before ActionView::Helpers are required. Not sure.

Can someone help me out here. Thank you.

A: 

I'd suggest creating a module for this, and including your module into the helper. Here's an example:

module AssetTagExtensions
  def self.included(base)
    base.alias_method_chain :existing_method, :added_cleverness
  end

  def existing_method_with_added_cleverness
    puts "Does foobar"
    existing_method_without_added_cleverness
  end
end

Then, in your init.rb file you should do something like:

ActionView::Helpers::AssetTagHelper.module_eval do
  include AssetTagExtensions
end

It's important to call module_eval (or send) on the ActionView::Helpers::AssetTagHelper class rather than reopening it, to ensure you don't prevent it from loading correctly.

tomafro