我怎样才能为Ruby重构这段代码?

时间:2012-11-07 11:11:41

标签: ruby refactoring

我创建了以下帮助器方法,它工作正常,但我想改进它的调用方式。

def display_if_present(attribute, i18key, hours=nil)
  unless attribute.blank?
    content_tag :li do

      if hours.present?
        concat content_tag :h2, get_translation_by_model_attr('achievment', i18key) + ' ('+t(:hours)+'): '
      else
        concat content_tag :h2, get_translation_by_model_attr('achievment', i18key)+': '
      end

      if i18key.include? 'date'
        concat content_tag :p, attribute.strftime('%m/%Y')
      elsif hours.present?
        concat content_tag :p, h(attribute) + "(" + t(:hours) + ")"
      else
        concat content_tag :p, h(attribute) 
      end
    end
  end
end

view方面,我有以下内容:

<%= display_if_present(academic_achievment.institution,'institution') %>

<%= display_if_present(academic_achievment.ativs_description,'ativs_description') %>

<%= display_if_present(academic_achievment.date_start,'date_start') %>

<%= display_if_present(academic_achievment.date_finished,'date_finished') %>

<%= display_if_present(academic_achievment.load, 'load', :hours) %>

<%= display_if_present(academic_achievment.tags, 'tags') %>

我想做一些重构。所以我试过了:

<% elements = %w(institution ativs_description date_start date_finished load tags) %>

<% elements.collect! do |item| %>
  <% params = (item == "load") ? "item, :hours" : "item" %>
  <%= display_if_present("academic_achievment.#{item}".constantize, params.constantize) %>
<% end %>

上面的代码块返回错误:

wrong constant name academic_achievment.institution
Extracted source (around line #15):

12: 
13:         <% elements.collect! do |item| %>
14:           <% params = (item == "load") ? "item, :hours" : "item" %>
15:           <%= display_if_present("academic_achievment.#{item}".constantize, params.constantize) %>
16:         <% end %>
17:  
18:       </ul>

我感谢一些更好的代码帮助。

1 个答案:

答案 0 :(得分:1)

我建议使用send方法,如下所示:

<% %w(institution ativs_description date_start date_finished load tags).each do |item| %>
  <%= display_if_present(academic_achievment.send(item), item, item == 'load' ? :hours : nil) %>
<% end %>