【问题标题】:Defaulting area_code to true for number_to_phone in rails将 rails 中 number_to_phone 的 area_code 默认为 true
【发布时间】:2015-12-02 05:01:31
【问题描述】:

我在我的应用程序中多次使用NumberHelpernumber_to_phone 方法。好像是这样的……

number_to_phone(phone_number, area_code: true)

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

【问题讨论】:

    标签: ruby-on-rails ruby helper


    【解决方案1】:

    一种方法是编写您自己的方法,该方法只接受电话号码参数和一些选项,将选项与: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
    

    这样,您可以只使用您的包装方法,而不必担心尝试修补原始方法。

    【讨论】:

    • 是的,甚至def num_to_phone(phone_number, options={area_code: true})
    • 不,因为您所拥有的不会,例如,让我在输出中添加扩展名。 num_to_phone(phone_number, extension: 555)
    • 我已对其进行了更新,以允许将其他选项传递到自定义方法中并与默认的{area_code: true}合并
    • 这更好,但您是在强制选择该选项,而不是优雅地退回到它。 pastebin 中的代码可能是个坏主意,应该给方法一个不同的名称,而不是调用 super? pastebin.com/4EKhJnCg
    【解决方案2】:

    我想这就是我要找的。​​p>

    # application_helper.rb
    
    def formatted_phone(number, options={area_code: true})
      number_to_phone(number, options)
    end
    

    【讨论】:

      【解决方案3】:

      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) 当通过迁移在表中添加新属性时,您可以设置区号的默认值,例如:-

      rails g migration add_default_value_to_table
      
      def change
          change_column :table_name, :area_code, :boolean, default: true
      end
      

      【讨论】:

      • number_to_phone 主要用于格式化数字以用于显示目的。这就是我使用它的方式。 ActionView::Helpers::NumberHelper
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多