Gena  Shumilkin
Gena Shumilkin

Reputation: 713

Sinatra: How to set namespace for base class

How to organize controllers hierarchy so that get something like this:

class ApplicationController < Sinatra::Application
  set :namespace, '/api' # ???
end

class UsersController < AplicationController
  namespace '/users' do
    # /api/users/show
    get '/show' do
      # blablabla
    end
  end
end

class PostsController < ApplicationController
  namespace '/posts' do
    # /api/posts/show
    get '/posts' do
      # blablabla
    end
  end
end

I'm mostly worked with Rails and dont know it is possible to do in Sinatra.

Upvotes: 1

Views: 1621

Answers (1)

ian
ian

Reputation: 12251

You just need to change one word:

class ApplicationController < Sinatra::Base

From Sinatra Up and Running:

Route Inheritance Not only settings, but every aspect of a Sinatra class will be inherited by its subclasses. This includes defined routes, all the error handlers, extensions, middleware, and so on. But most importantly, it will be inherited just the way methods are inherited. In case you should define a route for a class after having subclassed that class, the route will also be available in the subclass.

If you're looking for namespacing of the HTML route sort and not just the Ruby sort, then take a look at Sinatra Contrib which includes Sinatra Namespace.

If you do use Sinatra Namespace, you'd probably want to change one more word:

class PostsController < ApplicationController
  namespace '/posts' do
    # /api/posts/show
    get '/' do # otherwise the route would be /posts/posts
      # blablabla
    end
  end
end

Upvotes: 1

Related Questions