Ruby 是否可以在Sinatra中编写具有文件扩展名的根路由?
我正在用Sinatra编写一个JSON API,并使用Ruby 是否可以在Sinatra中编写具有文件扩展名的根路由?,ruby,routing,sinatra,Ruby,Routing,Sinatra,我正在用Sinatra编写一个JSON API,并使用map命令将不同的资源分成Sinatra::Base类: map('/people') { run Api::People } 在Api::People中,/People将被映射为根路径/。我希望通过Api::people处理/people.json——这可能吗?我不知道如何编写路由。看起来需要第二个映射: map('/people') { run Api::People } map('/people.json') { run A
map
命令将不同的资源分成Sinatra::Base
类:
map('/people') { run Api::People }
在
Api::People
中,/People
将被映射为根路径/
。我希望通过Api::people
处理/people.json
——这可能吗?我不知道如何编写路由。看起来需要第二个映射:
map('/people') { run Api::People }
map('/people.json') { run Api::People }
当我添加它时,/people.json
被发送到Api::people
的根路径
这种方法的问题是,我有很多嵌套的资源,它们转换成许多重复的映射 我已经确定了一个既优雅又符合逻辑的设计。您知道吗,一个
Sinatra::Base
类可以将其他Sinatra::Base
类作为中间件装载到自身内部
一旦我明白了这一点,解决方案显而易见:
config.ru
Dir['api/**/*.rb'].each {|file| require file }
run API::Router
api/router.rb
module API
class Router < Sinatra::Base
use Businesses
use People
use Users
get '*' do
not_found
end
end
end
class API::Businesses < Sinatra::Base
use Locations
get '/businesses.json' do ... end
get '/businesses/:id.json' do ... end
end
class API::Businesses < Sinatra::Base
class Locations < Sinatra::Base
before { @business = Business.find_by_id( params[:business_id] ) }
get '/businesses/:business_id/locations.json' do ... end
get '/businesses/:business_id/locations/:id.json' do ... end
end
end
模块API
类路由器
api/businesss.rb
module API
class Router < Sinatra::Base
use Businesses
use People
use Users
get '*' do
not_found
end
end
end
class API::Businesses < Sinatra::Base
use Locations
get '/businesses.json' do ... end
get '/businesses/:id.json' do ... end
end
class API::Businesses < Sinatra::Base
class Locations < Sinatra::Base
before { @business = Business.find_by_id( params[:business_id] ) }
get '/businesses/:business_id/locations.json' do ... end
get '/businesses/:business_id/locations/:id.json' do ... end
end
end
class-API::businesss
api/business/locations.rb
module API
class Router < Sinatra::Base
use Businesses
use People
use Users
get '*' do
not_found
end
end
end
class API::Businesses < Sinatra::Base
use Locations
get '/businesses.json' do ... end
get '/businesses/:id.json' do ... end
end
class API::Businesses < Sinatra::Base
class Locations < Sinatra::Base
before { @business = Business.find_by_id( params[:business_id] ) }
get '/businesses/:business_id/locations.json' do ... end
get '/businesses/:business_id/locations/:id.json' do ... end
end
end
class-API::businesss
另外一个好处是,所有路线都是完整的,因此您不必经常记住“/”实际映射到的是什么。如果您想要干衣机替代品:
%w(people people.json).each do |route|
map('/' + route) { run Api::People }
end
或者您可以在数组中包含斜杠,如
%w(/path/to/api/path/to/api.json)
,您可能需要查看它,因为它是为api构建的,您可以将它连接到Sinatra旁边app@daddz对我们来说可能不够成熟,但我会试试看。谢谢你的提示。