HUSTEN
HUSTEN

Reputation: 5197

How can I code this `if statement` within one line?

Is there any possible way to code this in one line? sometthing like <%= "A" if .......>

<% if @box == 'inbox' && m.is_read?(current_user) %>
A
<% else %>
B
<% end %> 

Upvotes: 1

Views: 73

Answers (3)

Dave Newton
Dave Newton

Reputation: 160321

A ternary gains you nothing but headache in the view layer; the logic should be in a helper, e.g.,

def inbox_msg_read?(box, msg)
  box == 'inbox' && msg.is_read?(current_user)
end

<%= inbox_msg_read?(@box, msg) ? 'A' : 'B' %>

Depending on what's actually happening here I might move the 'A'/'B' part into a helper as well.

I'd move the "inbox" logic to either a helper method or into the mailbox object:

box.inbox? && msg.is_read?(current_user)

This isolates inbox logic to a single location (e.g., not scattered across an arbitrary number of view files) and creates a single focal point if you need additional logic for other boxes (e.g., "trash" or something).

It also provides a hint that something metaprogrammatic might be useful for identifying boxes if there's any number of well-known boxes (e.g., trash, sent, today, etc.) It all depends on what's happening.

Scattering logic like this across the view layer makes refactorings less obvious, and forces multiple points of change when the logic/output needs change.

Upvotes: 0

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71019

A ternary operator will do the trick(see other answers for how to use it), but I advice you strongly against using it here. Using a ternary opperator you will reduce the code but your readability will suffer greatly for that.

Upvotes: 2

slhck
slhck

Reputation: 38790

You need a ternary operator – also known as the "conditional" operator in Ruby, which returns "A" if the expression before ? is true, and "B" if the expression is false.

<%= (@box == 'inbox' && m.is_read?(current_user)) ? "A" : "B" %>

Upvotes: 5

Related Questions