在辅助方法中分组 2 行代码

Grouping 2 lines of code in a helper method

我的 application_helper 中有一个方法和 2 行代码(方法中的最后一行)如果它们都处于活动状态则将无法工作。如何以正确的方式对它们进行分组? (选择代码行取决于用户打开的页面)。

def sortable(column, title = nil)
  title ||= column.titleize
  css_class = sort_column ? "current #{sort_direction}" : nil
  direction = sort_column && sort_direction == "asc" ? "desc" : "asc"
  link_to title, params.merge(sort: column, controller: 'analyze/consumptions', action: 'grid_report' , direction: direction), {class: css_class, remote: true, method: 'post'}
  link_to title, params.merge(sort: column, controller: 'admin/users', action: 'records' , direction: direction), {class: css_class}
end

只有 sortable 辅助方法中的 return 值会被添加到缓冲区。

您可以显式连接您希望包含的所有值(包括 link_to 的值)和 return 整个字符串。

def sortable(column, title = nil)
  title ||= column.titleize
  css_class = sort_column ? "current #{sort_direction}" : nil
  direction = sort_column && sort_direction == "asc" ? "desc" : "asc"

  "".html_safe.tap do |buffer|  # Be sure you do not have unsafe content when using html_safe
    buffer << link_to(title, params.merge(sort: column, controller: 'analyze/consumptions', action: 'grid_report' , direction: direction), {class: css_class, remote: true, method: 'post'})
    buffer << link_to(title, params.merge(sort: column, controller: 'admin/users', action: 'records' , direction: direction), {class: css_class})
  end  # The entire buffer will be returned.
end

注意:在我看来,将 sortable 分成两种不同的方法会更好,一种用于您希望呈现的每个 link。