curious_gudleif
curious_gudleif

Reputation: 572

Rails current url helper

Apologies for such a simple question, but I couldn't been able to solve it myself after hours since my RoR knowledge is basically nonexistent. In the Rails application I'm working with, has been used a navigation helper to highlight active menu:

  def nav_link(link_text, link_path, ico_path)
    class_name = current_page?(link_path) ? 'active' : nil

    content_tag :li do
      link_to(link_path, class: class_name) do
        image_tag("icons/#{ico_path}.svg") + content_tag(:span, link_text)
      end
    end
  end

The circumstances have changed and current_page? is no longer a viable option, since routing now handled on the front-end. Is there a way to achieve the same functionality by retrieving, for instance, current url and check it against link_path?. I've tried a lot of things with different helpers like request.original_url, but to no avail.

Upvotes: 6

Views: 16546

Answers (3)

Richard Peck
Richard Peck

Reputation: 76774

You'll want to look at the active_link_to gem:

def nav_link(link_text, link_path, ico_path)
    content_tag :li do
      active_link_to link_path do
        image_tag("icons/#{ico_path}.svg") + content_tag(:span, link_text)
      end
    end
end

Unlike the current_page? helper, active_link_to uses controller actions and model objects to determine whether you're on a specific page.

current_page? only tests against the current path, leaving you exposed if you're dealing with obscure or ajaxified routes.

--

I was going to write about how current_page? works etc, but since you mentioned that it's nonviable, I won't. I would have to question why it's nonviable though...

routing now handled on the front-end.

Surely even if you're using something like Angular with Rails, you'd have to set the routes for your app?

Upvotes: 2

Richard Hamilton
Richard Hamilton

Reputation: 26434

request.original_url should work according to the documentation.

Returns the original request URL as a string

http://apidock.com/rails/ActionDispatch/Request/original_url

You could also try string concatenation with different variables.

request.host + request.full_path

If that doesn't work either, you could try

url_for(:only_path => false);

Upvotes: 11

Related Questions