出于好奇:
这个(相当难看的)Rails代码如何被美化/重构:
def section_link(name, path)
link = link_to(name, path)
if name != controller.controller_name.titlecase
link
else
link_to(name, path, :class => 'current')
end
end
答案 0 :(得分:6)
def section_link(name, path)
options = {}
options[:class] = 'current' if name == controller_name.titlecase
link_to name, path, options
end
答案 1 :(得分:5)
我写道:
def section_link(name, path)
is_current = (name == controller.controller_name.titlecase)
link_to(name, path, :class => ('current' if is_current))
end
理由:1)变量is_current
使代码更具说明性。 2)link_to
假设nil
表示空类(我们想要的)。
答案 2 :(得分:1)
你可以这样做:
def section_link(name, path)
link_to(name, path, class: name == controller.controller_name.titlecase ? "current" : nil)
end
但这有点难以阅读。我会将班级决定分成另一种方法:
def section_link(name, path)
link_to(name, path, class: class_for(name) )
end
def class_for(name)
name == controller.controller_name.titlecase ? "current" : nil
end
答案 3 :(得分:0)
def section_link(name, path)
if name != controller_name.titlecase
link_to(name, path)
else
link_to(name, path, :class => 'current')
end
end
或类似的东西
def section_link(name, path)
link_to(name, path, :class => "#{"current" if name == controller_name.titlecase }")
end
如果有效的话,不要认为它真的需要重构......
答案 4 :(得分:0)
def section_link(name, path)
link_to(name, path,
*({class: "current"} if name == controller.controller_name.titlecase))
end