108

Just to help other developers, because there is no similar question on SO.

div class=(is_active? ? 'active' : 'inactive')
div class=('active' if is_active?)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Sergey Alekseev
  • 11,910
  • 11
  • 38
  • 53

3 Answers3

155

See the examples below:

div class=(is_active? ? 'active' : 'inactive')
div class=('active' if is_active?)

The same approach can be used to assign dynamic values to other attributes.

Sergey Alekseev
  • 11,910
  • 11
  • 38
  • 53
23

I use array of classes and nil element if there is no need to include class in list, then compact array to remove nil elements and finally join all together.

div class=(["cday", "col-md-1", day.day == 1 ? "col-md-offset-#{day.cwday-1}" : nil].compact.join(' '))
Oleg Kr
  • 469
  • 6
  • 8
12

If you have multiple conditions I am doing right now something like

div class=(('foo ' if is_foo?) + ('bar' if is_bar?))

Though I feel it to be a blemish if is_bar? return false and the generated HTML results in

<div class="foo "></div>

(the blemish is the blank character after the foo). If someone had a solution for that would be awesome.

Maxim Zubarev
  • 2,403
  • 2
  • 29
  • 48
  • 7
    Try `String#rstrip` in this case with 2 conditions: `div class=((('foo ' if is_foo?) + ('bar' if is_bar?)).rstrip)`. Or `div class=([('foo' if is_foo?), ('bar' if is_bar?)].compact.join(' '))` for several conditions. – Sergey Alekseev Jan 24 '14 at 22:55