Far too often I see something like this in my code.
<% if user_signed_in? %>
<%= link_to "Profile", profile_path(current_user) %>
<% elsif %>
<%= link_to "Sign In", sign_in_path %>
<% end %>
This works, but can be messy to read and hard to understand.
Fortunately, ActionView::Helpers::UrlHelper has a couple of features to increase readability and make your life easier.
When used, the helper “creates a link tag of the given name using a URL created by the set of options if condition is true, otherwise only the name is returned”.
This alone can make your code much easier to read.
# If you wanted "Profile" to be displayed at all times, guard adding the link
<% if user_signed_in? %>
<%= link_to "Profile", profile_path(current_user) %>
<% elsif %>
<%= "Profile" %>
<% end %>
# With link_to_if, you can simplify this down to just the following.
<%= link_to_if user_signed_in?, "Profile", profile_path(current_user) %>
In a more complex situation, you can use block syntax to specify what should be done instead.
<%=
link_to_if user_signed_in?, "Profile", profile_path(current_user) do
link_to "Sign In", signup_path
end
%>
The inverse relationship is also available link_to_unless.
For full documentation, see the docs.