开发者

Confirm on Apache Passenger deployment: rails access session in model

开发者 https://www.devze.com 2023-01-27 12:34 出处:网络
I am using this to access session in Model. http://www.zorched.net/2007/05/29/making-session-data-开发者_如何学Cavailable-to-models-in-ruby-on-rails/

I am using this to access session in Model.

http://www.zorched.net/2007/05/29/making-session-data-开发者_如何学Cavailable-to-models-in-ruby-on-rails/

Can anybody confirm that it will work with Apache + Passenger deployment too?

Or if there are any other alternatives to achieve the same?

Thanks,

Imran


I did not find any code on the internet that works, so I did some research and wrote my own. It works for Rails 3.2.x and probably on some other versions.

Insert this in your 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

I will not remind you that accessing your session from a model may lead to bad code. Other posts may tell you, that you are stupid. Though there are some valid reasons to access the session from your model, like implementing a Model.save method, that saves to the current users session.


Yes. It is the only efficient way I found to use session data in model. I also used it and never faced any deployment issue with Apache + passenger.

But you need to confirm when you will be playing with session values. On each new request to server, session value gets stored in thread and we can access it in model. If you are applying any logic by using thread value, then also make sure with situation when thread value might be nil also.

Because I got an issue where on development, my every code worked fine but on production, during starting server it caused an issue as initially it considered thread value as nil.

0

精彩评论

暂无评论...
验证码 换一张
取 消