Search code examples
ruby-on-railsrubyroutesurl-routing

Set rails redirections from YML file


I currently have one YML file with a bunch of redirections URLs inside, following a simple syntax old_url: new_url.

When I load this YML file on my app, I end up with a hash of keys and values.

At the moment, I'm not using this YML and all my redirections are added manually into a redirections file, which means I've got a very big file with more than 150 redirections added by hand, following this syntax:

get 'old_url', to: redirect('new_url', status: 301)

What I would like to do is to remove all these lines and use the "key/value" pairs that I have in my YML file instead. What is the best way to do this?

I thought it would be as easy as iterating on my hash inside my redirections file, but it does not seem to work and I'm not sure that's a really clean way of doing it

Thanks a lot


Solution

  • The following should work in your config/routes.rb:

    redirects = YAML.load_file(Rails.root.join('path/to/redirects.yaml'))
    redirects.each do |old, new|
      get old, to: redirect(new, status: 301)
    end
    

    Note that you need to change the path and file name to match the path and file name of your YAML file.