mc9
mc9

Reputation: 6349

Rails helper that to check conditional

I would like to know if checking conditions for the view is the correct use of helper.

Let's look at a contrived exmaple:

helper

def free_to_subscribe(product)
  current_user.active_member? && product.on_discount?
end

view

...
<% elsif free_to_subscribe(product) %>
  Free to subscribe!
<% end %>
...

I thought helpers needed return something to display in the view. Helpers that return boolean seem like a bit of a smell. Any ideas?

Upvotes: 0

Views: 105

Answers (1)

Jason Swett
Jason Swett

Reputation: 45074

I personally would have put it in a model:

class User < ActiveRecord::Base
  def free_to_subscribe?(product)
    active_member? && product.on_discount?
  end
end

Then the view would look like this:

...
<% elsif current_user.free_to_subscribe(product) %>
  Free to subscribe!
<% end %>
...

It's slightly more code in the view but otherwise it's like you're arbitrarily choosing to stick certain logic in helpers with no real reason, in my view.

Upvotes: 1

Related Questions