slim dynamic conditional class

Ruby on-RailsSlim Lang

Ruby on-Rails Problem Overview


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?)

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

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(' '))
    

Solution 3 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergey AlekseevView Question on Stackoverflow
Solution 1 - Ruby on-RailsSergey AlekseevView Answer on Stackoverflow
Solution 2 - Ruby on-RailsOleg KrView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMaxim ZubarevView Answer on Stackoverflow