Sinatra app的扩展

时间:2012-03-18 19:02:10

标签: ruby sinatra

我在Sinatra有一个简单的服务器,比如

require 'sinatra/base'

class Server < Sinatra::Base

  get '/' do
    "root"
  end

  get '/api/:apiname' do
    "return api from module #{params.apiname}"
  end

end

我希望能够为每个api包含模块,这些模块可以使用Sinatra DSL。它可能像:

module SomeApi
  get '/api_method'
    "result of api call"
  end
end

然后我想将SomeApi模块包含到我的Server类中,以便能够从URL“http:// localhost / someapi / api_method”获取api调用结果。是否可以更改我的代码以便能够执行此操作,还是应该使用另一个框架然后使用Sinatra?非常感谢!

1 个答案:

答案 0 :(得分:3)

也许你会发现Rack的map方法很有用。有了它,你可以做类似的事情:

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

启动服务器:

$ 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

测试它:

$ 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%