这很有效,但很冗长。如何缩短这个?
.service{:class => [route.night? ? "night" : "", route.school? ? "school" : ""] * ""}
我希望这个元素有:
class = "service"
如果不是route.night?
而不是route.school?
class = "night service"
如果route.night?
而非route.school?
class = "school service"
,如果不是route.night?
和route.school?
class = "school night service"
如果route.night?
和route.school?
编辑:matt帮我缩短了三个字符:
.service{:class => [route.night? ? "night" : "", route.school? ? "school" : ""]}
还能做些什么?
答案 0 :(得分:3)
我建议实施帮助
def service_class_helper(route)
classes = ['service']
classes << 'night' if route.night?
classes << 'school' if route.school?
classes
end
并相应地在模板中使用
:class => service_class_helper(route)
如果不需要使用助手,您可以使用
.service{:class => ['night', 'school'].select { |c| c if route.send("#{c}?") } }
这项工作很简单。但是必然存在一些明显的局限性。
答案 1 :(得分:2)
您可以这样做:
.service{class: {night: route.night?, school: route.school?}.map{|k,v| k if v} }
或者,如果您可以重构Route
课程,则可以将其定义为:
class Route
def initialize(night: false, school: false)
@route_type = Set.new
@route_type.add('night') if night
@route_type.add('school') if school
end
def route_type
@route_type.to_a
end
def night?
@route_type.include? 'night'
end
def school?
@route_type.include? 'school'
end
end
现在你可以写
了.service { class: route.route_type }