0

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?

jbk
  • 1,911
  • 19
  • 36
  • Possible duplicate of [Best way to highlight current page in Rails 3? -- apply a css class to links conditionally](https://stackoverflow.com/questions/8552763/best-way-to-highlight-current-page-in-rails-3-apply-a-css-class-to-links-con) – hjpotter92 Jun 19 '17 at 09:12
  • Thanks for the link, a nice solution, I'd like to try to use the rails helper though to do this, in the end I wrote a helper method as written below and suggested by @Surya – jbk Jun 19 '17 at 09:53

2 Answers2

1

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.

Surya
  • 15,703
  • 3
  • 51
  • 74
0

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>
jbk
  • 1,911
  • 19
  • 36