Access URL Helpers in routes.rb

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

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

So /privacypolicy.php is redirected to the correct page, defined right above it.

However, he throws the following error:

 undefined local variable or method `privacy_policy_url' 

So, I assume that you cannot use the URLs in route.rb. Is there a way to use the helpers URLs in the route file and is it advisable to do this?

+7
source share
3 answers

I know I'm a little late here, but this question is one of the best hits when googling "uses url_helpers in routes.rb" and I initially found it when I came across this problem, so I share my solution.

As @martinjlowm noted in his answer, helper URLs cannot be used when creating new routes. However, there is one way to define a redirect route rule using URLs. The fact is that ActionDispatch :: Routing :: Redirection # redirect can take a block (or #call -able), which later (when the user types a route), called by two parameters, params and a request to return a new route, a string. And since the routes are correctly configured at the moment, it is quite possible to call the calling URLs inside the block!

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

In addition, we can use Ruby metaprogramming tools to add 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 
+4
source

Helper URLs are created using routes. Therefore, they will not be used when drawing new routes.

You will need to use the geyavat approach.

- or -

Redirect using the exact URL, e.g. http://guides.rubyonrails.org/routing.html .

edit:

If this is more than just one "... php" route, you might want to create a redirect controller. Take a look here on how to do this: http://palexander.posterous.com/provide-valid-301-redirects-using-rails-route

Inside the routes file, you must add this at the bottom so that it does not interfere with other routes:

 get '/:url' => 'redirect#index' 
+1
source

Something like:

 get 'privacypolicy.php' => "privacy_policy#show" 
0
source

All Articles