【问题标题】:Override image_tag rails helper覆盖 image_tag rails 助手
【发布时间】:2014-07-02 11:31:35
【问题描述】:
有没有办法覆盖 Rails 3.x 中 asset_tag_helper.rb 中的 image_tag 辅助方法?
如果图像扩展名为svg,目标是自动添加带有png 版本图像的data-fallback,而不必一直手动添加。
我搜索但到目前为止一无所获。
编辑:
我找到了Override rails helpers with access to original,但它似乎不是我想要的,我更愿意创建自己的类来扩展 Rails 原生帮助器,然后覆盖该方法。这可能吗?
【问题讨论】:
标签:
ruby-on-rails
image
overriding
【解决方案1】:
我终于用 已弃用 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
如果您有更好的解决方案或对当前解决方案有任何改进,请分享。
我看到我也可以使用super,但是我不明白代码是怎么写的。