0

我正在将一些视图代码重构为辅助方法,我想知道是否可以进一步简化它。

# In the view...

<%= navigation_link params[:controller], 'accounts', account_path %>

# ApplicationHelper

def navigation_link(controller_name, page_name, path_name)
  if controller_name == page_name
    content_tag :li, "#{page_name.capitalize.singularize}", :class => 'current'
  else
    content_tag :li, link_to("#{page_name.capitalize.singularize}", path_name)
  end
end

将字符串 'accounts' 与路由辅助方法名称 account_path 一起传递似乎是多余的。

我真的需要传入第三个参数 path_name,还是可以在 navigation_link 帮助器中使用作为第二个参数传入的字符串来生成它?

4

2 回答 2

2

我猜你的助手已经是 Rails 的一部分了。它被称为link_to_unless_current(可点击)

例子:

<li><%= link_to_unless_current("Home", { :action => "index" }) %></li>
于 2012-05-07T15:23:52.250 回答
0

解决方案是使用 Object#send。

# The view simplifies to this...

<%= navigation_link params[:controller], 'accounts' %>

# ...and the ApplicationHelper becomes...

def navigation_link(controller_name, page_name)
  if controller_name == page_name
    content_tag :li, "#{page_name.capitalize.singularize}", :class => 'current'
  else
    content_tag :li, link_to("#{page_name.capitalize.singularize}", send("#{page_name.singularize}_path")
  end
end
于 2012-05-07T17:31:03.703 回答