有没有办法覆盖Rails 3.x中image_tag
中的asset_tag_helper.rb
辅助方法?
目标是,如果图片扩展名为data-fallback
,则自动添加png
图片的svg
版本,而不必一直手动执行此操作。
我搜索但到目前为止一无所获。
修改:
我发现Override rails helpers with access to original但它似乎不是我想要的,我宁愿创建我自己的类,扩展Rails本机助手,然后覆盖该方法。这可能吗?
答案 0 :(得分:0)
我最后使用已弃用的 alias_method_chain
。
<强>配置/初始化/ 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
如果您有更好的解决方案或有关当前解决方案的任何改进,请分享。
我看到我也可以使用super
,但我并不了解编写代码的位置。