HAML - if / elsif construction HAML - if / elsif construction ruby ruby

HAML - if / elsif construction


@Ingenu's helper method looks like the smarter approach, but if you don't mind it quicker and dirtier, you could do:

- if something1  -divclass = 'a'- elsif something2  -divclass = 'b'- elsif something3  -divclass = 'c'- else  -divclass = 'd'%div{:class => divclass}  %div another content


I think you should create a helper method instead:

%div{:class => helper_method(useful_parameters)}

The really ugly way to accomplish this is with ternary operators (condition ? true_case : false_case) which doesn't sound like a good solution given from the fact that you selected haml and want to have your code base clean.


You could extend your if condition with this module and then use smalltalk-style conditions

  module IfTrue    def ifTrue &block      yield if self      slf=self      o = Object.new      def o.elseIf val, &block         yield if !slf && val      end    end  end

now you could code stuff like this:

  condition.extend(IfTrue).ifTrue{    do_stuff   }elseIf(condition2){    doOtherStuff  }

or, if you are a naughty monkey patcher ;-):

 Object.include IfTrue condition.ifTrue{     do_stuff  }elseIf(condition2){    doOtherStuff }

if you want to chain more than one elseif you will have to adapt this code by somehow factoring the elsif definition