“patch”rails渲染function可编辑默认选项

当我渲染:在rails中的xml我总是想要:dasherize => false选项。 有没有办法将应用程序范围设置为默认值,当然不必修改rails源代码?

也许是一个渲染函数,它以某种方式优先于第一个,然后使用此选项调用它…

当其他人来看你的代码时,做这样的事情确实有可能导致意外行为的缺点(即直到他们发现你的被覆盖的方法,他们可能想知道为什么当没有明确指定时它表现得像dasherize false。 )也就是说,在ApplicationController或您的某个特定控制器中,您可以覆盖render方法。

例如:

class MyController < ApplicationController def render(options = nil, extra_options = {}, &block) options ||= {} # initialise to empty hash if no options specified options = options.merge(:dasherize => false) if options[:xml] super(options, extra_options, &block) end end 

如果你想在你的调用渲染中允许dasherize仍然可以覆盖你可以在另一个方向上进行哈希合并,例如

 options = {:dasherize => false}.merge(options) 

您也可以尝试这样的溶剂:

 alias_method_chain :render, :no_dasherize def render_with_no_dasherize(options = nil, extra_options = {}, &block) new_options = options new_options = {:dasherize=>false}.merge(options) if(options[:xml]) render_without_no_dasherize(new_options, extra_options, &block) end 

您可以将它放在Application Controller中(这样所有控制器都会被感染)或仅在特定的控制器中。