【问题标题】:Want to DRY this code but have trouble想要 DRY 这段代码但是遇到了麻烦
【发布时间】:2012-01-25 06:53:59
【问题描述】:

我有两种方法可以做类似的事情。我是一个菜鸟,想知道如何将这些组合成一个方法:

#test if the current selected language is the one that was clicked in the menu
def link_to_without_class_unless_current_language(language)
  if language_selected?(language)
    content_tag(:li, content_tag(:span, content_tag(:em, language)), :class => "current")
  else
    content_tag :li, link_to(content_tag(:span, language), :locale => language.prefix)
  end
end


#tests if the current page is the same as that for the link
def link_to_without_class_unless_current(name, options)
  if current_page?(options[:url])
    content_tag(:li, content_tag(:span, content_tag(:em, name)), 
                :class => options[:class] ||= "current")
  else
    content_tag :li, link_to(content_tag(:span, name), options[:url])
  end
end

在视图中:

<%= link_to_without_class_unless_current_language 'English'  %> |
<%= link_to_without_class_unless_current_language 'Français' %>

<%= link_to_without_class_unless_current t('application.menu_links.home'), 
                                         { :url => root_url } %>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 refactoring dry


    【解决方案1】:

    我是否建议您简单地传递一组选项,就像您在第二种方法中的第二个参数一样,您可以在其中验证选项 [:url],您可以验证是否设置了选项 [:语言],然后执行您的第一个方法的代码中的代码,否则如果设置了 option[:url] 执行第二种方法的代码,您也可以提供选项 :name 。

    所以你的 3 个电话看起来像这样

    <%= link_to_without_class_unless_current :language => 'English'  %> |
    <%= link_to_without_class_unless_current :language => 'Français' %>
    
    <%= link_to_without_class_unless_current :name => t('application.menu_links.home'), 
                                             :url => root_url  %>
    

    【讨论】:

    • 谢谢安德鲁,我想这就是我要做的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2020-11-02
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 2020-09-02
    相关资源
    最近更新 更多