Tonči D.
Tonči D.

Reputation: 464

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 }

Upvotes: 6

Views: 899

Answers (2)

Ben Sheldon
Ben Sheldon

Reputation: 1104

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

Upvotes: 2

rlarcombe
rlarcombe

Reputation: 2986

If you are defining the route of 'new-page' immediately above, why do you need to use the path helper at all? Isn't this all you need?

get 'old-page', to: redirect('new-page')

Or am I missing something?

If you need dynamic segments, you can still do something like:

get 'old-page/:this_is_dynamic', to: redirect('new-page/%{this_is_dynamic}')

Upvotes: 0

Related Questions