Question

Is there a way to override the image_tag helper method located in the asset_tag_helper.rb in Rails 3.x?

The goal is to automatically add a data-fallback with the png version of the image if the image extension is svg, to not have to do it manually all the time.

I search but found nothing so far.

Edit:

I found Override rails helpers with access to original but it doesn't seem to be what I want, I would prefer to create my own class that extends Rails native helper and then override the method. Is that possible?

Was it helpful?

Solution

I finally did it using the deprecated alias_method_chain.

config/initializers/asset_tag_helper.rb

module ActionView::Helpers::AssetTagHelper

  # Override the native image_tag helper method.
  # Automatically add data-fallback
  def image_tag_with_fallback(source, options = {})
    ext = File.extname(source)
    fallback_ext = 'png'

    # Allow custom extension, even if it will probably always be "png".
    if options.key? 'fallback_ext'
      fallback_ext = options.fallback_ext
      options.delete :fallback_ext
    end

    if ext == '.svg'
      # If fallback is provided, don't override it.
      if !(options.key?('data') && options.data.key?('fallback'))
        # Ensure to have an object.
        if !options.key?('data')
          options['data'] = {}
        end

        # Replace the extension by the fallback extension and use the asset_path helper to get the right path.
        options['data']['fallback'] = asset_path (source.sub ext, '.' + fallback_ext)
      end
    end

    image_tag_without_fallback(source, options) # calling the original helper
  end

  alias_method_chain :image_tag, :fallback
end

If you have a better solution or any improvment about the current solution, please share. I saw that I could also use super, but I didn't understand how neither where write the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top