如何重构这些Rails代码?

时间:2012-10-07 20:00:51

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

出于好奇:

这个(相当难看的)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  

5 个答案:

答案 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