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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With