rails 中的 number_to_phone 默认 area_code 为 true

Defaulting area_code to true for number_to_phone in rails

我在我的应用程序中多次使用 NumberHelpernumber_to_phone 方法。看起来像这样...

number_to_phone(phone_number, area_code: true)

但从来没有一个地方我希望 area_code 成为 false。我应该如何让它默认为 true?

实现此目的的一种方法是编写您自己的方法,该方法仅采用 phone 数字参数和一些选项,将选项与 :area_code 的默认值合并,然后调用 #number_to_phone。您可以在 ApplicationHelper 中这样做:

# application_helper.rb

def num_to_phone(phone_number, opts={})
  opts = {area_code: true}.merge(opts)
  number_to_phone(phone_number, opts)
end

这样,您就可以只使用包装器方法,而不必担心尝试对原始方法进行猴子修补。

1) 你可以通过回调方法设置area_code: true:-

Class Model
    before_create :set_area_code_to_true

    private
    def set_area_code_to_true
        self.area_code = true
    end
end

2) 当通过迁移在 table 中添加新属性时,您可以设置区号的默认值,例如:-

rails g migration add_default_value_to_table

def change
    change_column :table_name, :area_code, :boolean, default: true
end

我想这就是我要找的。

# application_helper.rb

def formatted_phone(number, options={area_code: true})
  number_to_phone(number, options)
end