Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing URL helpers in routes.rb

I would like to redirect a path in routes using the following lines:

get 'privacy_policy', :controller => :pages, :as => 'privacy_policy'
get 'privacypolicy.php' => redirect(privacy_policy_url)

So that /privacypolicy.php gets redirected to the correct page defined right above it.

However, it's throwing the following error:

undefined local variable or method `privacy_policy_url'

So I'm guessing one cannot use URL helpers in routes.rb. Is there a way to use URL helpers in the route file, and is it advisable to do so?

like image 521
David Verhasselt Avatar asked Mar 22 '12 12:03

David Verhasselt


2 Answers

I know I'm a little late here, but this question is one of the top hits when googling "use url_helpers in routes.rb", and I initially found it when I had stumbled upon this problem, so I'd like to share my solution.

As @martinjlowm mentioned in his answer, one cannot use URL helpers when drawing new routes. However, there is one way to define a redirecting route rule using URL helpers. The thing is, ActionDispatch::Routing::Redirection#redirect can take a block (or a #call-able), which is later (when the user hits the route) invoked with two parameters, params and request, to return a new route, a string. And because the routes are properly drawn at that moment, it is completely valid to call URL helpers inside the block!

get 'privacypolicy.php', to: redirect { |_params, _request|
  Rails.application.routes.url_helpers.privacy_policy_path
}

Furthermore, we can employ Ruby metaprogramming facilities to add some sugar:

class UrlHelpersRedirector
  def self.method_missing(method, *args, **kwargs) # rubocop:disable Style/MethodMissing
    new(method, args, kwargs)
  end

  def initialize(url_helper, args, kwargs)
    @url_helper = url_helper
    @args = args
    @kwargs = kwargs
  end

  def call(_params, _request)
    url_helpers.public_send(@url_helper, *@args, **@kwargs)
  end

  private

  def url_helpers
    Rails.application.routes.url_helpers
  end
end

# ...

Rails.application.routes.draw do
  get 'privacypolicy.php', to: redirect(UrlHelperRedirector.privacy_policy_path)    
end
like image 163
nameless Avatar answered Sep 28 '22 03:09

nameless


URL Helpers are created from the routes. Therefore they won't be usable when drawing new routes.

You will have to use gayavat's approach.

-- or --

Redirect using the exact URL like http://guides.rubyonrails.org/routing.html does.

edit:

If it's more than just the one '...php' route, you might want to consider making a redirect controller. Take a look here, how to se it up: http://palexander.posterous.com/provide-valid-301-redirects-using-rails-route

Inside your routes file, you should add this at the bottom, so it doesn't interfere with other routes:

get '/:url' => 'redirect#index'
like image 32
martinjlowm Avatar answered Sep 28 '22 05:09

martinjlowm