Question

This works, but is verbose. How to shorten this?

.service{:class => [route.night? ? "night" : "", route.school? ? "school" : ""] * ""}

I would like this element to have:

  • class = "service" if not route.night? and not route.school?
  • class = "night service" if route.night? and not route.school?
  • class = "school service" if not route.night? and route.school?
  • class = "school night service" if route.night? and route.school?

EDIT: matt helped me shorten this by three characters:

.service{:class => [route.night? ? "night" : "", route.school? ? "school" : ""]}

What else can be done?

No correct solution

OTHER TIPS

I would suggest implementing a helper

def service_class_helper(route)
  classes = ['service']
  classes << 'night' if route.night?
  classes << 'school' if route.school?
  classes
end

and use it in your template accordingly

:class => service_class_helper(route)

If the use of a helper is not desired you can have something like

.service{:class => ['night', 'school'].select { |c| c if route.send("#{c}?") } }

Which does the job quite simple. But is bound to some obvious limitations.

You can do something like this:

.service{class: {night: route.night?, school: route.school?}.map{|k,v| k if v} }

Or, if you can refactor your Route class you can define it like:

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

And now you could write

.service { class: route.route_type }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top