Wilko
Wilko

Reputation: 5

Better ways to return HTML from a method in rails?

this is my first post here so be nice ;-)

I am currently learning the ropes of RoR (and general programming concepts) and I'm not sure if how I am returning some data from a method is 'the right way' (or maybe the 'rails way') to do so.

I have a form that a user can enter a value into and my 'app' will poll the requested data from an external web service.

In my view, I have a table to contain said data and in one cell I've included a call to the following method:

extract of view:

<tr>
<td>Subscriber</td>
<%= is_subscribed?(@search_result.expiry) %>
</tr>

So, I'm calling this little is_subscribed? method (which I've stored in a helper) as per below:

def is_subscribed?(sub_date)
  if sub_date >= Date.today
    return '<td class="text-success">Yes</td>'.html_safe
  else
    return '<td class="bg-danger">No</td>'.html_safe
  end
end

Depending on the result of the comparison, I return some HTML with one class and a value or some HTML with another class.

The above does work and the class is applied correctly in the resulting HTML. What I would like to know is whether there a simpler way to do this, is this way bad practise? I am also curious how would someone else handle this sort of task.

Thanks!

Upvotes: 0

Views: 2134

Answers (1)

mahemoff
mahemoff

Reputation: 46379

It's fine how you've done it. Here's a variant:

def subscribed_td(sub_date)
  sub_date >= Date.today ?
    content_tag(:td, 'Yes', class: 'text-success') :
    content_tag(:td, 'No', class: 'bg-danger')
end

The main difference is simply the function name is more accurate imo, as I'd expect a function called is_subscribed? to return a boolean. It's also using content_tag to be a bit more concise, and a ternary instead of the if-then (which is not to everyone's taste). You could try to be fancy here with just a single content_tag expression and then use ternaries inside it to vary the arguments, but that's OTT DRY-ness imo.

Upvotes: 1

Related Questions