如何在 Sinatra 控制器中使用参数

How to use params in a Sinatra controller

我正在尝试以 Rails 风格编写 Sinatra:

#in app.rb
 get '/' do 
   # params request and response are accessible here
   SomeController.new.some_method
 end

我无法访问控制器中的 paramsrequestresponse

  class SomeController < Sinatra::Base
    def some_method
      #params are nil here
   end
  end

我可以通过从 app.rb 作为参数传递来做到这一点,但我希望它表现得像 Rails。

我要做的是制作一个接受 params/request/response 作为初始化参数的基本控制器:

require 'sinatra'
require 'byebug'

class BaseController
  attr_reader :params, :request, :response
  def initialize(sinatra_app)
    @params   = sinatra_app.params
    @request  = sinatra_app.request
    @response = sinatra_app.response
  end
end

class SomeController < BaseController
  def some_method
    {
      params:   params.class.name,
      request:  request.class.name,
      response: response.class.name,
    }.to_json
  end
end

get '/' do
  SomeController.new(self).some_method
end

然后测试:

$ curl localhost:4567

响应是:

{
  "params":"Sinatra::IndifferentHash",
  "request":"Sinatra::Request",
  "response":"Sinatra::Response"
}

显示所有 3 个变量都可从当前上下文中获得