【问题标题】:Rails radio_button refactoring best practiceRails radio_button 重构最佳实践
【发布时间】:2013-10-01 18:52:21
【问题描述】:

我实际上在我的 Rails 项目中使用了表单助手radio_button。当一切正常时,代码本身对我来说并不好看:

_form.html.haml

#- Loop on durations types
- Product::DURATIONS.each_with_index do |name, index|
  #- If new record, then select the first index by default
  - unless @product.duration_type.present?
    - checked = (index == 0) ? true : false
  - else
    #- Otherwise, if edit, then select the product value
    - checked = (name == @product.duration_type) ? true : false
  = f.radio_button :duration_type, name, checked: checked
  = f.label :duration_type, name

product.rb

DURATIONS = %w( Hour Day Week Month Year )

有没有更好的方法以更 DRY 和 Rails 的方式编写此代码?

非常感谢

【问题讨论】:

    标签: ruby-on-rails refactoring radio-button


    【解决方案1】:

    不知道这是否是 Rail 的方式,但它是一种有趣的方式并且可以节省一些线路。

    这个想法是将对象持续时间的索引与循环中的当前索引进行比较。如果@product.duration_type 不在Product::DURATIONS 或nil 中,它返回nil,它被to_i 转换为整数,给出0 或第一个单选按钮。

    #- Loop on durations types
    - Product::DURATIONS.each_with_index do |name, index|
      - checked = Product::DURATIONS.index(@product.duration_type).to_i == index
      = f.radio_button :duration_type, name, checked: checked
      = f.label :duration_type, name
    

    其他选项更具可读性。

    #- Loop on durations types
    - Product::DURATIONS.each_with_index do |name, index|
      - checked = @product.duration_type ? (name == @product.duration_type) : (index == 0)
      = f.radio_button :duration_type, name, checked: checked
      = f.label :duration_type, name
    

    【讨论】:

    • 更改了第二种方法,因为其中存在错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    相关资源
    最近更新 更多