如何从Rails中访问Rack环境? [英] How do I access the Rack environment from within Rails?

查看:73
本文介绍了如何从Rails中访问Rack环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的Rack应用程序:

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

将Rack应用程序挂接到Rails之后,如何从Rails中访问env["hello"]?

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

更新:感谢Gaius的回答.使用Rack and 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

推荐答案

我很确定您可以使用Rack::Request对象传递请求范围变量:

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

或者,您可以直接获得该"env"对象:

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

这篇关于如何从Rails中访问Rack环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆