Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confirm on Apache Passenger deployment: rails access session in model

I am using this to access session in Model.

http://www.zorched.net/2007/05/29/making-session-data-available-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

like image 702
Saim Avatar asked Nov 25 '10 18:11

Saim


2 Answers

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.

like image 105
iblue Avatar answered Oct 23 '22 13:10

iblue


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.

like image 21
Nimesh Nikum Avatar answered Oct 23 '22 12:10

Nimesh Nikum