0

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

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>

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

4

1 回答 1

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 %>
于 2012-11-07T12:06:04.417 回答