我有一个页脚助手来显示链接
def footer_helper
resources = ["tweet","questions"] # and perhaps something more
resources.map do |resource|
if current_page?(controller: resource.pluralize, action: 'index')
link_to "New #{resource.humanize}", {controller: resource.pluralize, action: 'new'}
else
link_to "#{resource.pluralize.humanize}",{controller: resource.pluralize, action: 'index'}
end
end.join(" ")
end
并在footer.html.erb中写道:
<%= raw footer_helper %>
问题:
.join(" ")
非常丑陋。这有更好的语法吗?如果我不使用它,.map
将返回一个包含链接html的数组。 答案 0 :(得分:1)
def footer_helper
["tweet","questions"].map do |resource|
if current_page?(controller: resource.pluralize, action: 'index')
link_to "New #{resource.humanize", send(:"new_#{resource}_path")
else
link_to resource.pluralize.humanize, send(:"index_#{resource}_path")
end
end.join(" ").html_safe
end
并在 footer.html.erb 中简单地说:
<%= footer_helper %>
答案 1 :(得分:0)
我认为连接很好,但是你实例化了一个你不需要的变量。此外,您可以使用发送路径。代码如下。
def footer_helper
["tweet","questions"].map do |resource|
if current_page?(controller: resource.pluralize, action: 'index')
link_to "New #{resource.humanize}", send("new_#{resource}_path".to_sym)
else
link_to "#{resource.pluralize.humanize}", send("index_#{resource}_path".to_sym)
end
end.join(' ')
end