只是出于好奇:
这个(相当丑陋的)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
只是出于好奇:
这个(相当丑陋的)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
def section_link(name, path)
options = {}
options[:class] = 'current' if name == controller_name.titlecase
link_to name, path, options
end
我会写:
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
意味着空类(我们在这里想要的)。
你可以这样做:
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
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
不要认为它真的需要重构,如果它有效......
def section_link(name, path)
link_to(name, path,
*({class: "current"} if name == controller.controller_name.titlecase))
end