ruby - Sinatra helper to fake a request -


summary

within sinatra web app, how can make virtual request application , response body text? example, these routes...

get('/foo'){ "foo" } get('/bar'){ "#{spoof_request '/foo'} - bar" } 

...should result in response "foo - bar" when requesting "/bar" web browser.

motivation

my application has page representing bug entry, lots of details bug entry: version bug experienced in, how important it, tags associated it, whom bug assigned, etc.

the user may edit individual pieces of data on page interactively. using ajaxfetch jquery plugin, javascript uses ajax swap out read-only section of page (e.g. name of person bug assigned to) html partial form editing section. user submits form, , ajax makes new request static version of field.

in order dry, want haml view creates page use exact same request ajax makes when creating individual static pieces. example:

#notifications.section   %h2 email me if someone...   .section-body= spoof_request "/partial/notifications/#{@bug.id}" 

not-quite-working code

the following helper defining spoof_request worked under sinatra 1.1.2:

path_vars = %w[ request_path path_info request_uri ] def spoof_request( uri, headers=nil )   new_env = env.dup    path_vars.each{ |k| new_env[k] = uri.to_s }    new_env.merge!(headers) if headers   call( new_env ).last.join  end 

under sinatra 1.2.3, however, no longer works. despite setting each of path_vars desired uri, call( new_env ) still causes sinatra process route current request, not specified path. (this results in infinite recursion until stack level bottoms out.)

this question differs calling sinatra within sinatra because accepted answer (old) question not maintain session of user.

the code using more complex answer in sinatra readme, relied on same mechanism. neither code nor answer readme worked under 1.2.3 due bug in version. both work under 1.2.6.

here's test case of simple helper works:

require 'sinatra' helpers   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 

Comments