我可以在视图助手中动态生成路径助手方法吗?

时间:2012-05-07 15:03:08

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

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

# 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助手中生成它吗?

2 个答案:

答案 0 :(得分:2)

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

示例:

<li><%= link_to_unless_current("Home", { :action => "index" }) %></li>

答案 1 :(得分: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