Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Rails route helpers in route redirect block

Is there a convenient way to access route helpers in the route redirect block?

get 'new-page' => 'home#new_page', as: :new_page

get 'old-page', to: redirect(:new_page)
# or something like:
get 'old-page', to: redirect { |_, _| new_page_path }

Edit:

This solution works, but it's ugly:

get 'old-page', to: redirect { |_, _| Rails.application.routes.url_helpers.new_page_path }
like image 940
Tonči D. Avatar asked Nov 13 '15 11:11

Tonči D.


1 Answers

It looks like OP solved their own problem, but I wanted to Answer that this is a good solution:

get 'old-page', to: redirect { Rails.application.routes.url_helpers.new_page_path }

And if one gets tired of writing Rails.application.routes.url_helpers it's easy to define a helper method for that:

Rails.application.routes.draw do
  get 'old-page', to: redirect { url_helpers.new_page_path }
  get 'another-page', to: redirect { url_helpers.new_page_path }

  def url_helpers
    Rails.application.routes.url_helpers
  end
end

like image 132
Ben Sheldon Avatar answered Oct 13 '22 22:10

Ben Sheldon