Sinatra Helper to Fake a Request

Sinatra helper to fake a request

The code I was using is more complex than the answer in the Sinatra README, but relied on the same mechanism. Neither my code nor the answer from the README worked under 1.2.3 due to a bug in that version. Both now work under 1.2.6.

Here's a test case of a simple helper that works:

require 'sinatra'
helpers do
def local_get(url)
call(env.merge("PATH_INFO" => url)).last.join
end
end
get("/foo"){ "foo - #{local_get '/bar'}" }
get("/bar"){ "bar" }

In action:

phrogz$ curl http://localhost:4567/foo
foo - bar

Calling Sinatra from within Sinatra

I was able to hack something up by making a quick and dirty rack request and calling the Sinatra (a rack app) application directly. It's not pretty, but it works. Note that it would probably be better to extract the code that generates this resource into a helper method instead of doing something like this. But it is possible, and there might be better, cleaner ways of doing it than this.

#!/usr/bin/env ruby
require 'rubygems'
require 'stringio'
require 'sinatra'

get '/someresource' do
resource = self.call(
'REQUEST_METHOD' => 'GET',
'PATH_INFO' => '/otherresource',
'rack.input' => StringIO.new
)[2].join('')

resource.upcase
end

get '/otherresource' do
"test"
end

If you want to know more about what's going on behind the scenes, I've written a few articles on the basics of Rack you can read. There is What is Rack? and Using Rack.

Sinatra Run Method on Every Request

You can use before:

before do
# authentication
end

Stubbing Sinatra helper in Cucumber

You can get the right context by using Sinatra::Application.class_eval

Edit: See original poster's answer for full explanation.

Monkeypatching from a Sinatra helper

You can use the Module#included method to do this. I think you will need to modify your class definition slightly to use class_eval. I've tested the following and it works as expected:

module Sinatra
module FooHelper
def self.included(mod)
::Numeric.class_eval do
def my_new_method
return "whatever"
end
end
end
end
end

Sinatra request[SOME_HEADER] doesn't work on POST; doc bug?

Seems to be a bug in the documentation. request[] actually retrieves the params for the request, not the header:

https://github.com/rack/rack/blob/master/lib/rack/request.rb#L262

def [](key)
params[key.to_s]
end

I double checked it by testing also. Seems a bit silly, but it looks like you really can't directly access the header in any way except through env. At least I could not figure out any other way.

Processing a request that depends on two clicks in Sinatra

I didn't end up using JQuery to register the clicks. I basically created a querystring to register the locations of the clicks and used server-side programming to determine when to execute a move.

Sinatra always prints '!! Invalid request on standard output

Uninstall & reinstall Sinatra and Ruby



Related Topics



Leave a reply



Submit