How to use the `link_to_unless_current` helper to work for both current or root path?

253 Views Asked by At

I am setting up my navbar link_to's and I'm trying to stop a link being rendered if current_path is the same as link_path or if current path is the same as root path, as root path is defined as that same as the link path, as below:

_navbarhtml.erb

        <ul class="nav navbar-nav navbar-right">
         <% if user_signed_in? %>               
           <li><%= link_to_unless_current('My Quotes', quotes_path(current_user)) do %></li>
         <% end %>
           <li><%= link_to_unless_current('New Quote', new_quote_path) do %></li>
         <% end %>
           <li><%= link_to('My Account', edit_user_registration_path) %></li>
           <li><%= link_to "Sign out", destroy_user_session_path, :method => :delete %></li>
         <% else %>
           <li><%= link_to('Sign in', new_user_session_path) %></li>
           <li><%= link_to('Sign up', new_user_registration_path) %></li>
         <% end %>
        </li>

routes.rb

root    'quotes#new'

Any neat suggestions as to how to nicely write this?

2

There are 2 best solutions below

0
Surya On

You can try current_page?. Create a helper method like so:

def link_to_unless_current(text, url, options={})
  if current_page?(url)
    # do something else? maybe create a text which does not have a link?
  else
    link_to text, url, options
  end
end

Now, view will be like:

<%= link_to_unless_current('My Quotes', quotes_path(current_user)) %>

Feel free to change the name of helper method.

0
jbk On

Thanks Surya, this is the way i got it to work in the end:

application_helper.rb

def link_to_unless_current_or_root(text, url)
    if current_page?(url) 

    elsif current_page?(root_path)

    else
        link_to text, url
    end
end

_navbar.html.erb

<li><%= link_to_unless_current_or_root('New Quote', new_quote_path) %></li>