Created
March 2, 2016 02:24
-
-
Save oddlyfunctional/b11e42e65ab24b096262 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Guest(session) { | |
this.session = session; | |
this.name = "Anonymous"; | |
this.avatar = session.avatar || "https://api.adorable.io/avatars/128/" + Math.random(); | |
session.avatar = this.avatar; | |
} | |
Guest.prototype.getCart = function() { | |
this.cart = this.cart || Cart.find(this.session.cartId) || Cart.create(); | |
return cart; | |
}; | |
Guest.prototype.setCart = function(cart) { | |
this.cart = cart; | |
} | |
Guest.prototype.save = function(cart) { | |
this.session.cartId = cart && cart.id; | |
return true; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Guest | |
def initialize(session) | |
self.session = session | |
end | |
def name | |
"Anonymous" | |
end | |
def avatar | |
session[:avatar] ||= "https://api.adorable.io/avatars/128/#{rand}" | |
end | |
def cart | |
@cart ||= Cart.find_by(id: session[:cart_id]) || Cart.create | |
end | |
def cart=(cart) | |
@cart = cart | |
end | |
def save | |
session[:cart_id] = cart && cart.id | |
true | |
end | |
def persisted? | |
false | |
end | |
private | |
attr_accessor :session | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've made some changes to reproduce a little better the
ActiveRecord::Base
s behavior, only "saving" the data, meaning writing to the session, when thesave
function is called.