Brice Sanchez
Brice Sanchez
Senior web developer in Québec city (Canada).
Quebecrb.com founder. Refinery CMS Core Team member.
· 1 min read

[TIL] How to override Spree Rails engine routes

First post of my Today I Learned [TIL] serie.

Overriding a rails engine routes can be hard to achieve when you want to remove or change existing routes.

The fastest way to achieve this, is to fork the Rails engine’s repository, Spree e-commerce in my case, and make changes on its config/routes.rb file.

It’s easy, it works but… it will be a pain to stay synced with the official project’s repository.

So we have to find a better way and finally the solution is pretty simple :

# config/application.rb
module MyRailsApp
  class Application < Rails::Application

    # Override Spree Core routes in order to translate products routes
    initializer "delete_spree_core_routes", after: "add_routing_paths" do |app|
      new_spree_core_route_path = File.expand_path('../../config/spree_core_routes_override.rb', __FILE__)
      routes_paths = app.routes_reloader.paths

      spree_core_route_path = routes_paths.select{ |path| path.include?("spree_core") }.first

      if spree_core_route_path.present?
        spree_core_route_path_index = routes_paths.index(spree_core_route_path)

        routes_paths.delete_at(spree_core_route_path_index)
        routes_paths.insert(spree_core_route_path_index, new_spree_core_route_path)
      end
    end

    [...]
  end
end

By defining this initializer in your config/application.rb file, you will be able to interact with the load process of the rails engines routes in your app and using your custom routes file (spree_core_routes_override.rb) instead of the original spree_core routes file.

Let me know if this solution helped you or if you know a better solution!

Brice Sanchez
I’m a senior web developer in Québec City (Canada), Ruby programming language specialist, Quebec.rb founder and Refinery CMS Core Team member.