I use session to store my shopping cart object
in my cart model I have
def initialize
@items = Array.new
end
def clean
@items = Array.new
end
I want to use session to store whole cart object so I can use the method above
like this
@cart = session[:cart] ||= Cart.new
but my @cart output is strange
first time run it output
<%= @cart %>
#<Cart:0x007efc844d3af0>
<% @cart.clean %>
true
everything is fine, but the second time it output the object's content
<%= @cart %>
{"items"=>[]}
<% @cart.clean %>
undefined method `clean'
Can session store the whole object?
Or there is something I did wrong?
Thanks.
EDIT:
<% session[:cart] = Cart.new %>
<%= session[:cart] %>
#<Cart:0x007efc868be0a0>
<% session[:cart] = session[:cart] ||= Cart.new %>
<%= session[:cart] %>
#<Cart:0x007efc868be0a0> #Because session[:cart] does not exist
<% session[:cart] = session[:cart] ||= Cart.new %>
<%= session[:cart] %>
{"items"=>[]} #Session does not store the cart object but store the cart object's content
EDIT 2:
<% @cart = session[:cart] ||= Cart.new %>
<%= @cart %> #session[:cart] is nil so print Cart.new
<br>
<% session[:cart] = Cart.new %>
<% @cart = session[:cart] ||= Cart.new %>
<%= @cart %> #session[:cart] isn't nil so print session[:cart]
I got both two outputs are Cart object
when I refresh the page and run the same code
<% @cart = session[:cart] ||= Cart.new %>
@cart should be the session[:cart] because the session is not nil and the session[:cart] should be Cart object but it output "{"items"=>[]}"
EDIT 3:
First time:
<%= session[:cart] %>
-> nil
<% session[:cart] = Cart.new %>
<%= session[:cart] %>
-> <Cart:0x00000007c112c0>
Second time:
<%= session[:cart] %>
-> {"items"=>[]} #Why it isn't a Cart object after I refresh?
<% session[:cart] = Cart.new %>
<%= session[:cart] %>
-> <Cart:0x00000007c112c0>