Reputation: 3180
I have a simple server in Sinatra, like
require 'sinatra/base'
class Server < Sinatra::Base
get '/' do
"root"
end
get '/api/:apiname' do
"return api from module #{params.apiname}"
end
end
I want to be able to include modules for each api, which could use Sinatra DSL. It could be like:
module SomeApi
get '/api_method'
"result of api call"
end
end
Then I want to include SomeApi
module to my Server
class, to be able to get api call result from url "http://localhost/someapi/api_method". Is it possible to change my code to be able to do this, or should I use another framework then Sinatra? Thanks a lot!
Upvotes: 2
Views: 289
Reputation: 54684
Maybe you will find the map
method from Rack useful. With it, you could do something like:
config.ru:
require 'sinatra/base'
require './app'
map('/api1'){ run API1 }
map('/api2'){ run API2 }
map('/'){ run Server }
app.rb:
class Server < Sinatra::Base
get '/' do
"root"
end
get '/foo' do
"foo from Server"
end
end
class API1 < Sinatra::Base
get '/foo' do
"foo from API1"
end
end
class API2 < Sinatra::Base
get '/foo' do
"foo from API2"
end
end
start server:
$ thin start
>> Using rack adapter
>> Thin web server (v1.3.1 codename Triple Espresso)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:3000, CTRL+C to stop
test it:
$ curl localhost:3000
root%
$ curl localhost:3000/foo
foo from Server%
$ curl localhost:3000/api1/foo
foo from API1%
$ curl localhost:3000/api2/foo
foo from API2%
Upvotes: 3