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.