Brandon
Brandon

Reputation: 1875

Why can't I override #asset_path from ActionView?

I am working on upgrading an app to Rails 5, and #asset_path now raises if the url is nil. I'm trying to monkey patch that method with a version that will work like Rails 4 so that I can get my tests passing.

I've spent hours on this, and I'm going crazy. For some reason no matter what I do, I can't monkey patch the module. I thought this initializer would work:

module ActionView
  module Helpers
    module AssetUrlHelper
      alias asset_path_raise_on_nil asset_path

      def asset_path(source, options = {})
        return '' if source.nil?
        asset_path_raise_on_nil(source, options)
      end
    end
  end
end

I also tried putting my method in another module and includeing, prepending, and appending it to both ActionView::Helpers::AssetUrlHelper and ActionView::Helpers::AssetTagHelper.

No matter what I do, I can't get my method to be executed. The only way I can alter the method is to bundle open actionview and changing the actual method.

Upvotes: 1

Views: 80

Answers (1)

Brandon
Brandon

Reputation: 1875

I figured out that it is because #asset_path is simply an alias. I needed to override the method which the alias points at:

module ActionView
  module Helpers
    module AssetTagHelper
      alias_method :path_to_asset_raise_on_nil, :path_to_asset

      def path_to_asset(source, options = {})
        return '' if source.nil?
        path_to_asset_raise_on_nil(source, options)
      end
    end
  end
end

Upvotes: 1

Related Questions