确认 Apache Passenger 部署:模型中的 Rails 访问会话

2023-11-22

我正在使用它来访问模型中的会话。

http://www.zorched.net/2007/05/29/making-session-data-available-to-models-in-ruby-on-rails/

有人能确认它也适用于 Apache + Passenger 部署吗?

或者是否有其他替代方案可以达到相同的效果?

Thanks,

Imran


我在互联网上没有找到任何有效的代码,所以我做了一些研究并编写了自己的代码。它适用于 Rails 3.2.x,也可能适用于其他一些版本。

将此插入您的ApplicationController

  # Set a filter that is invoked on every request
  before_filter :_set_current_session

  protected
  def _set_current_session
    # Define an accessor. The session is always in the current controller
    # instance in @_request.session. So we need a way to access this in
    # our model
    accessor = instance_variable_get(:@_request)

    # This defines a method session in ActiveRecord::Base. If your model
    # inherits from another Base Class (when using MongoMapper or similar),
    # insert the class here.
    ActiveRecord::Base.send(:define_method, "session", proc {accessor.session})
  end

我不会提醒您从模型访问会话可能会导致错误的代码。其他帖子可能会告诉你,你很蠢。尽管有一些充分的理由从模型访问会话,例如实现Model.save方法,保存到当前用户会话。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

确认 Apache Passenger 部署:模型中的 Rails 访问会话 的相关文章

随机推荐