0

What is the best way to add classes to table cells in rails based on differing criteria for each cell?

For example...I have a date cell: If the date is coming up on 10 days from that date, need to add a "upcoming-due" class. Or if the date is past today, add a "past-due" class.

On another cell, based on a string, it needs to have a class "on" or "off".

I'm not sure how to do this, but I do know I probably shouldn't have a bunch of logic in the views...

Please advise.

Kevin Brown
  • 12,602
  • 34
  • 95
  • 155

2 Answers2

0

You could accomplish it with something like this:

class="#{(@date - Time.now <= 10.days) ? upcoming_due : '' %>"

However, as you mentioned, it's not good to have a lot of logic in the view. If you find yourself repeating the same code, you can add helper methods which look like this:

def upcoming(date)
  (date - Time.now <= 10.days) ? 'upcoming_due' : ''
end

def past(date)
  (date - Time.now <= 10.days) ? 'past_due' : ''
end

In your view, you'd have something like this:

class="#{ upcoming(@date).presence || past(@date).presence || '' }"

John
  • 485
  • 2
  • 5
  • 15
  • So I can reference those actions in the view, from the controller? Does it have to be my entry controller? How does rails know where to find those methods? – Kevin Brown Apr 25 '13 at 20:35
  • You can access helper methods in your views. I think Rails finds those methods through naming convention. `app/views/user/*` would use `app/helpers/user_helper.rb`. If it's a utility you want over multiple views, then you might put it in `app/helpers/application_helper.rb` – John Apr 25 '13 at 20:47
0

This sounds like something I'd do with Knockout in the browser. Basically you create a knockout model with an observable field for each field in your database, and computed fields to figure out the class names or whatever based on those fields. You then use data-bind attributes in the HTML template to bind to knockout's computed fields.

Drawbacks to this approach is that users will need to have javascript enabled for the classes to be applied correctly, and you put a bit of logic in the javascript. But I think javascript files are a fine place to put display logic.

sockmonk
  • 4,195
  • 24
  • 40
  • In that case, why wouldn't I just use jQuery? Probably the most straight-forward approach, right? – Kevin Brown Apr 25 '13 at 20:34
  • Using javascript for this doesn't pass the smell test. You'll end up with a frail DOM for displaying static content. – John Apr 25 '13 at 20:51
  • @John, The smell test? Frail DOM? – Kevin Brown Apr 25 '13 at 20:57
  • If it isn't changing dynamically, knockout might be overkill, and you could do it with just jquery. If you want to avoid using javascript for it though, I'd opt for a presenter object rather than helpers. – sockmonk Apr 25 '13 at 21:31