bcoughlan
bcoughlan

Reputation: 26627

Ruby / Rails: only pass parameter if condition is true

I have a line of HAML like this:

%li{:id=>node.shortcode, :class=>liclass unless liclass.empty? }

which doesn't work. I only want to pass the 'class' parameter if the condition provided isn't true. Is there a nice way to do this in Ruby will I just have to use an if/else?

Upvotes: 1

Views: 3009

Answers (3)

Natalie Weizenbaum
Natalie Weizenbaum

Reputation: 5964

%li{:id=>node.shortcode, :class=>(liclass unless liclass.empty?)}

Upvotes: 1

Larsenal
Larsenal

Reputation: 51146

Try this:

%li{({:id=>node.shortcode}.merge(liclass.empty? ? {} : {:class=>liclass}) )}

It's not pretty, but it gives you the markup you're after.

Upvotes: 4

methyl
methyl

Reputation: 3312

It shouldn't assign class when liclass will be empty, but I'm not sure.
Try this:
%li{:id=>node.shortcode, :class=>liclass }

Upvotes: 0

Related Questions