views:

2771

answers:

4

How can I treat important session info as if it were a model?

I've started toying with it, and some of it works. But I'm not sure what I'm missing? Does anyone know a good place to start or where I can find some good examples?

Also, I'm able to use the model to set session variables, but what about getting them from the model as opposed to always using session[:blah]... How can I retrieve them from the model instead?

class Cart
  attr_reader :items

  def initialize(session)
    @session = session
    @session[:cart] ||= []
    @items ||= session[:cart]
  end

  def add_rooms(new_rooms,startdate,days)
    #remove 0 values
    new_rooms.delete_if {|k, v| v == "0" }
    rooms = []
    new_rooms.each do |k, v|
      #rname = Room.find(k)
      #night = Available.find_by_room_id(k)
      rooms << {:room_id => k, :people => v, :no_days => days, :startdate => startdate} 
    end

    @session[:cart] = rooms
    #@items = rooms

  end

end
A: 
John Topley
I saw it. but it was rather brief on the subject.
holden
+1  A: 

There are some gotchas to be taken into account with this approach

  1. Depending on your session storage system, your session may grow too big if the objects you are putting in it are complex. The default store for sessions in Rails 2.3 are cookies so there will definitely be a limit imposed by the browser.
  2. If your model changes, after deploying your app users with old sessions will be presented with objects marshalled from the old model definitions, so they may get unexpected errors.
pantulis
There's not a lot i want to put in there, just a date, and some ids. So I'm not worried about space, but it will get replaced often and by different controllers.
holden
A: 

+1 on the Railscast by Ryan Bates.

This type of thing works for me;

  def set_order_id(i)
    @cart_session[:order_id] = i
  end
  def has_order_id?
    @cart_session[:order_id]
  end
  def order_id
    has_order_id?
  end
revgum
A: 

You just need a method that returns the data you want from the session.

def blah
  @session[:blah]
end

If you need a lot of these, I would create a plugin that extends Class with a method that works similarly to attr_reader. Something like

session_reader :blah
GhettoDuk