Reputation: 13571
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
Upvotes: 3
Views: 8864
Reputation: 24
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
Upvotes: 1
Reputation: 1187
+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
Upvotes: 1
Reputation: 1705
There are some gotchas to be taken into account with this approach
Upvotes: 2
Reputation: 115292
Upvotes: 1