Rob
Rob

Reputation: 7216

Each do according to convention

I know ruby/ rails is all about convention so I thought I'd ask what the appropriate way to do something like this is:

  <% @event.prices.each do |price| %>
      <% price_value = price.price > 0 ? "FREE" : price.price %> <!-- ** this line ** -->
      <% if price.name.length > 0 %>
          <div>$<%= price_value %> - <%= price.name %></div>
      <% else %>
          <div>$<%= price_value %> - Ticket Type <%= price.id + 1 %></div>
      <% end %>
  <% end %>

As you can see, I'm setting price_value to avoid a huge set of if statements, but my gut is telling me that there is a more appropriate way to do this in ruby. Any suggestions?

Upvotes: 1

Views: 48

Answers (1)

CDub
CDub

Reputation: 13354

Depends on what prices is... It looks like a relation. If it is, then you have a Price object, which you could put a method on, call it value or something like that, which does your logic for you:

class Price < ActiveRecord::Base

  def value
    self.price > 0 ? "FREE" : self.price
  end

end

Then in your view, you would just be able to call price.value:

<% @event.prices.each do |price| %>
  <% if price.name.length > 0 %>
    <div>$<%= price.value %> - <%= price.name %></div>
  <% else %>
    <div>$<%= price.value %> - Ticket Type <%= price.id + 1 %></div>
  <% end %>
<% end %>

You could follow the same convention with name as well... Something like:

class Price < ActiveRecord::Base

  def value
    self.price > 0 ? "FREE" : self.price
  end

  def get_name
    self.name.present? ? self.name : "Ticket Type #{self.id + 1}"
  end

end

Then your view would look like:

<% @event.prices.each do |price| %>
  <div>$<%= price.value %> - <%= price.get_name %></div>
<% end %>

Since I'm on a roll (and obviously had way too much caffeine today), then you could create a helper method which would give you $<%= price.value %> - <%= price.get_name %>

module PriceHelper

  def generate_price_value_and_name(price)
    "$#{price.value} - #{price.get_name}"
  end

end

Now your view would be:

<% @event.prices.each do |price| %>
  <div><%= generate_price_value_and_name(price) %></div>
<% end %>

Upvotes: 3

Related Questions