0

OK, stupid newbie question: how do you make a line break only when it's needed?

I'm creating a basic address listing and only want to include a line of an address if it isn't blank. How do I keep the blank line from printing? I've tried including the break and new line tags, and tried using puts and quotation marks of both varieties and escaping the slashes but can't seem to display the address correctly.

Is there a way to have each line of the address to print on its own line or simply omit the line if there is no info to put on it?

Here's the current version of the code:

<p><strong>Main Address</strong></p>
    <p><%= if @vendor.address1 || null
             @vendor.address1  #need a break here
           end %>
      <%= if @vendor.address2 || null
             @vendor.address2 #need a break here
           end %>
      <%= @vendor.city %>, <%= @vendor.state %> <%= @vendor.zip %></p>
AnkitG
  • 6,438
  • 7
  • 44
  • 72

2 Answers2

2

This is how I would do it:

<p>
  <strong>Main Address</strong>
</p>
<p>
<% unless @vendor.address1.blank? %>
  <%= @vendor.address1 %><br>
<% end %>
<% unless @vendor.address2.blank? %>
  <%= @vendor.address2 %><br>
<% end %>
  <%= @vendor.city %>, <%= @vendor.state %> <%= @vendor.zip %>
</p>

By the way: the || null in your code is not valid Ruby. null does not exist, it should be nil. But even if you had used nil, your code does not do what you expect it to do. For these kind of things, you'd better use blank?.

Community
  • 1
  • 1
Mischa
  • 42,876
  • 8
  • 99
  • 111
  • Thanks so much! I wondered if the blank? or exists? methods would be better. However, I'm now getting some sort of syntax error: " syntax error, unexpected ')', expecting keyword_then or ';' or '\n' " ...nless @vendor.address2.blank? );@output_buffer.safe_concat('
    I'll keep working on it to figure out what I'm doing wrong.
    – Katherine Chalmers Sep 10 '12 at 03:00
  • There was a small mistake in the answer I posted. Sorry. Could you try again with the code above? – Mischa Sep 10 '12 at 03:03
-1
<p><strong>Main Address</strong></p>
        <p><%= @vendor.address1%><%= <br/> if @vendor.address1.blank? %>
          <%=  @vendor.address2%><%= <br/> if @vendor.address2.blank? %>
          <%= @vendor.city %>, <%= @vendor.state %> <%= @vendor.zip %></p>
AnkitG
  • 6,438
  • 7
  • 44
  • 72
  • This does give the desired result. Please fix your answer. Personally I don't think it's clean, because you *have to* provide an `else` clause where there's no need for one. – Mischa Sep 10 '12 at 02:57
  • This isn't the ternary operator anymore. `
    ` has to be in quotes and it should be `unless` instead of `if`.
    – Mischa Sep 10 '12 at 03:28