Rails:在请求范围内共享信息 [英] Rails: share information within a Request scope

查看:51
本文介绍了Rails:在请求范围内共享信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rails 中在当前请求范围内共享信息的机制是什么?

What's the mechanism in Rails to share information within the current request scope?

熟悉 Asp.Net 的人会知道有一个 HttpContext 可供在请求期间调用的所有实体使用.

Those familiar with Asp.Net would know there is a HttpContext that is available to all the entities that are invoked during a request.

Rails 中有没有类似的东西?

Anything similar in Rails?

推荐答案

使用 around_filterThread.current[] 您可以轻松创建请求上下文/范围.请参阅以下示例.

With around_filter and Thread.current[] you can easily create a request context/scope. See the following example.

首先添加您的application_controller.rb:

  around_filter :request_context

  def request_context
    begin
      RequestContext.begin_request
      yield
    ensure
      RequestContext.end_request
    end
  end

现在将以下类添加到 lib/request_context.rb

class RequestContext
  def self.instance
    i = Thread.current[:request_context]
    unless i
      raise "No instance present. In script/rakefiles: use RequestContext.with_scope {}, " +
            "in controller: ensure `around_filter :request_scope` is configured"
    end
    return i
  end

  # Allows the use of this scope from rake/scripts
  # ContextScope.with_scope do |scope|
  #   # do something
  #   ...
  # end
  def self.with_scope
    begin
      begin_request
      yield(instance)
    ensure
      end_request
    end
  end

  def self.begin_request
    raise "request_context already set" if Thread.current[:request_context]
    Thread.current[:request_context] = RequestContext.new
  end

  def self.end_request
    raise "request_context already nil" unless Thread.current[:request_context]
    Thread.current[:request_context] = nil
  end

  # user part, add constructors/getters/setters here

  def initialize
    # you can setup stuff here, be aware that this
    # is being called in _every_ request.
  end
end

这很简单.您可以将数据存储在 RequestContext.instance 对象中,该对象将在每次请求后重新创建.

This is pretty straightforward. You can store data in the RequestContext.instance object, the object will get recreated after every request.

这篇关于Rails:在请求范围内共享信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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