Search code examples
ruby-on-railsruby-on-rails-5

How to handle route not found within a namespace in Rails?


I am trying expose our app via public APIs. I have written API code as an engine and mounted it on my app.

Say I have defined a route /api/users which will be handled by the API engine i have created.

We also have a generic path defined at the end of routes definition which handles all other routes since we use a frontend framework.

If the user misspells the public API as /api/user-detail, it gets handled in the generic path defined.

routes.rb

mount FtApi::Engine => "/api"
match "*a", controller: :assets, action: :index, via: [:get, :post, :patch]

I want to handle any undefined routes error under namespace api within the engine, but the path is captured by wildcard route controller.

How can i handle undefined routes error under namespace api within the Rails engine defined?


Solution

  • You can stop capturing any random route by your wildcard by applying Request-Based Constraints.

    For more Info take a look here Request Based Constraints and Advanced Constraints

    Take a look at the given below code. Haven't tested this but this is an example how you can add constraints in routes.

    match "*a", controller: :assets, action: :index, constraints: RouteConstraint.new, via: [:get, :post, :patch]
    

    And then add this code in constraints or initializers

    class RouteConstraint
      def matches?(request)
        not request.path.include?('api')
      end
    end