Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the Rack environment from within Rails?

I have a Rack application that looks like this:

class Foo   def initialize(app)     @app = app   end   def call(env)     env["hello"] = "world"     @app.call(env)   end end 

After hooking my Rack application into Rails, how do I get access to env["hello"] from within Rails?

Update: Thanks to Gaius for the answer. Rack and Rails let you store things for the duration of the request, or the duration of the session:

# in middleware def call(env)   Rack::Request.new(env)["foo"] = "bar"  # sticks around for one request    env["rack.session"] ||= {}   env["rack.session"]["hello"] = "world" # sticks around for duration of session end  # in Rails def index   if params["foo"] == "bar"     ...   end   if session["hello"] == "world"     ...   end end 
like image 692
Michael Gundlach Avatar asked May 11 '09 15:05

Michael Gundlach


People also ask

What is ENV in rack?

Basically the env is a hash version of the request object specific to the web server. Rack does some work to give a normalized env so the middleware can behave consistently across web servers. Follow this answer to receive notifications.

What is rack server in Rails?

Rack provides a minimal, modular, and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.

What is Rack middleware in rails?

Rack middleware is a way to filter a request and response coming into your application. A middleware component sits between the client and the server, processing inbound requests and outbound responses, but it's more than interface that can be used to talk to web server.

What is Rack app?

Rack is a modular interface between web servers and web applications developed in the Ruby programming language. With Rack, application programming interfaces (APIs) for web frameworks and middleware are wrapped into a single method call handling HTTP requests and responses.


1 Answers

I'm pretty sure you can use the Rack::Request object for passing request-scope variables:

# middleware: def call(env)   request = Rack::Request.new(env) # no matter how many times you do 'new' you always get the same object   request[:foo] = 'bar'   @app.call(env) end  # Controller: def index   if params[:foo] == 'bar'     ...   end end 

Alternatively, you can get at that "env" object directly:

# middleware: def call(env)   env['foo'] = 'bar'   @app.call(env) end  # controller: def index   if request.env['foo'] == 'bar'     ...   end end 
like image 90
James A. Rosen Avatar answered Sep 22 '22 15:09

James A. Rosen