ActionView::Helpers::NumberHelper
方法很喜欢一个nubmer_with_precision
采取precision
选项,默认值是3
。如何重写的“::的ActionView ::助手方法NumberHelper`默认选项
我想设置的默认值3
到2
。
哪里应该写重写方法 而如何重写方法仅仅只有默认值
ActionView::Helpers::NumberHelper
方法很喜欢一个nubmer_with_precision
采取precision
选项,默认值是3
。如何重写的“::的ActionView ::助手方法NumberHelper`默认选项
我想设置的默认值3
到2
。
哪里应该写重写方法 而如何重写方法仅仅只有默认值
可以猴补丁在初始化该方法。创建一个,或在config/initializers
中将以下内容添加到初始化程序中。
require 'action_view'
module ActionView::Helpers::NumberHelper
alias_method :__number_with_precision, :number_with_precision
private :__number_with_precision
def number_with_precision(number, options = {})
options = {precision: 2}.merge(options)
__number_with_precision(number, options)
end
end
您可以创建自己的类写的另一种方法:??
class Foo
extend ActionView::Helpers::NumberHelper
def self.my_custom_number_with_precision(number, precision = 2)
number_with_precision(number, precision: precision)
end
end
Foo.my_custom_number_with_precision(22) #=> "22.00"
Foo.my_custom_number_with_precision(121.41256) #=> "121.41"
是的,我可以创建另一个方法,但我想覆盖现有方法的默认选项。 – ironsand
我固定的错字和名字'配置/初始化/ number_with_precision.rb'下救了你的代码,并重新启动服务器的轨道,但'逗号后3位数字number_with_precision'显示依然。任何猜测我做错了什么? – ironsand
@ironsand抱歉,错字,现在修复并添加了需要的库部分。我之前没有测试过代码,但现在在我的本地环境中进行了测试。您可以先尝试使用'number_with_precision(3.123456,precision:2)'而不使用此修补程序,以查看它是否有效。如果没有,那么您使用的Rails版本中可能会出现一些命名问题。您可能需要找出控制精度的参数名称,并相应地更新补丁。您需要重新启动您的rails应用程序才能在初始化程序中引入更新。 –
谢谢,它现在完美的工作! – ironsand