How to use params in a Sinatra controller

Viewed 473

I'm trying to write Sinatra in Rails style:

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

I'm not able to access params, request or response in the controller:

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

I can do it by passing as an argument from app.rb but I want it to behave like Rails.

1 Answers

What I would do is make a base controller which accepts the params/request/response as initialization parameters:

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

Then testing:

$ curl localhost:4567

The response is:

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

Showing that all 3 variables are available from the current context

Related