【问题标题】:Is it possible to write a root route with a file extension in Sinatra?是否可以在 Sinatra 中编写带有文件扩展名的根路由?
【发布时间】:2011-08-12 12:40:06
【问题描述】:

我正在使用 Sinatra 编写 JSON API,并使用 map 命令将不同的资源分成 Sinatra::Base 类:

map('/people') { run Api::People }

Api::People 内,/people 将被映射为根路径/。我希望通过Api::People 处理/people.json——这可能吗?我不知道怎么写路线。

【问题讨论】:

  • 您可能想看看github.com/intridea/grape,因为它是为 API 构建的,您可以将它连接到您的 Sinatra 应用程序旁边
  • @daddz 对我们来说可能不够成熟,但我会尝试一下。感谢您的提示。

标签: ruby routing sinatra


【解决方案1】:

如果您想要 DRYer 替代品:

%w(people people.json).each do |route|
  map('/' + route) { run Api::People }
end

或者您可以在数组中包含斜线,例如 %w(/path/to/api /path/to/api.json)

【讨论】:

    【解决方案2】:

    看起来需要第二个映射:

    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
    

    api/businesses.rb

    class API::Businesses < Sinatra::Base
      use Locations
    
      get '/businesses.json' do ... end
      get '/businesses/:id.json' do ... end
    end
    

    api/businesses/locations.rb

    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
    

    另一个好处是所有路由都是完整的,因此您不必经常记住“/”实际映射到什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 2013-04-26
      • 2019-06-26
      • 2016-05-18
      • 1970-01-01
      相关资源
      最近更新 更多