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

时间:2015-10-16 11:47:18

标签: ruby-on-rails ruby methods helper

我的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

1 个答案:

答案 0 :(得分:1)

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

您可以显式连接您希望包含的所有值(均为link_to),并返回整个字符串。

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分成两个不同的方法,每个方法对应一个链接。