1

ActionView::Helpers::NumberHelper methods liked a nubmer_with_precision take precision option and default value of it is 3.

I want to set the default value 3 to 2.

Where should I write override method? And how to override the methods just only default value?

ironsand
  • 14,329
  • 17
  • 83
  • 176

2 Answers2

3

You can monkey patch this method in the initializers. Create one, or append the following to a initializer in 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

Alternate Approach

It may not be a good idea to override the internal methods like this as it may lead to unexpected results in codebase being worked by several developers. A better approach is to override the defaults via config/locales/en.yml as explained in this answer.

Kulbir Saini
  • 3,926
  • 1
  • 26
  • 34
Arie Xiao
  • 13,909
  • 3
  • 31
  • 30
  • I fixed typo and saved you code under the name `config/initializer/number_with_precision.rb`, and restart rails server, but `number_with_precision` shows still 3 digits after comma. Any guess what I am doing wrong? – ironsand Dec 21 '15 at 01:47
  • @ironsand sorry for the typo, fixed now and added the require library part. I didn't test the code before, but now tested in my local environment. You can first try `number_with_precision(3.123456, precision:2)` without this patch to see if this works. If it doesn't, there may be some naming issue in the Rails version you use. You may need to find out what is the parameter name that controls the precision and update the patch accordingly. You need to restart your rails application to bring in the updates in the initializers. – Arie Xiao Dec 23 '15 at 14:47
1

You can create your own class to write another method:

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"
Lei Chen
  • 81
  • 6