Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 477
curious_gudleif Avatar asked Jan 11 '16 02:01

curious_gudleif


People also ask

How do I get the current URL in Ruby on Rails?

You can write request. url instead of request. request_uri . This combines the protocol (usually http://) with the host, and request_uri to give you the full address.

What is the best way to get the current request URL in Rails?

What is the best way to get the current request URL in Rails? You should use request. original_url to get the current URL.

What are URL Helpers rails?

Module ActionView::Helpers::UrlHelper. Provides a set of methods for making links and getting URLs that depend on the routing subsystem (see ActionDispatch::Routing). This allows you to use the same format for links in views and controllers.


1 Answers

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);

like image 106
Richard Hamilton Avatar answered Oct 07 '22 04:10

Richard Hamilton