Lee McAlilly
Lee McAlilly

Reputation: 9316

What is the more concise way to structure this if/else statement in Ruby?

I have the following statement in a Rails project, but there has to be a more compact way to write it:

<% if current_user.present? %>
  <%= link_to "Edit", edit_artist_path(artist) %>
<% end %>

<% if current_user.present? && current_user.admin? %>
 | <%= link_to "delete", artist, method: :delete,
                            data: { confirm: "You sure?" } %>
<% end %>

There has to be a more compact way to express this. I thought that if elsif end would work but that is giving me an error. What is the better way to write this?

Upvotes: 0

Views: 53

Answers (1)

Ziv Galili
Ziv Galili

Reputation: 1445

If you are using devise gem to handle user sessions you can use user_signed_in? instead of current_user.present?

Lets assume that you don't, few ways to do it:

1:

<% if current_user.present? %>
  <%= link_to "Edit", edit_artist_path(artist) %>
  <%= link_to "delete", artist, method: :delete, data: { confirm: "You sure?" } if current_user.admin? %>
<% end %>

2:

<%= link_to "Edit", edit_artist_path(artist) if current_user.present? %>
<%= link_to "delete", artist, method: :delete, data: { confirm: "You sure?" } if current_user.present? && current_user.admin?%>

3: you can create helper method called admin_signed_in? that will check and return current_user.present? && current_user.admin?

Using devise:

1:

<% if user_signed_in? %>
  <%= link_to "Edit", edit_artist_path(artist) %>
  <%= link_to "delete", artist, method: :delete, data: { confirm: "You sure?" } if current_user.admin? %>
<% end %>

2:

<%= link_to "Edit", edit_artist_path(artist) if user_signed_in? %>
<%= link_to "delete", artist, method: :delete, data: { confirm: "You sure?" } if user_signed_in? && current_user.admin?%>

Upvotes: 1

Related Questions