Skip to content

Instantly share code, notes, and snippets.

@oddlyfunctional
Created March 2, 2016 02:24
Show Gist options
  • Save oddlyfunctional/b11e42e65ab24b096262 to your computer and use it in GitHub Desktop.
Save oddlyfunctional/b11e42e65ab24b096262 to your computer and use it in GitHub Desktop.
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;
}
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
@oddlyfunctional
Copy link
Author

I've made some changes to reproduce a little better the ActiveRecord::Bases behavior, only "saving" the data, meaning writing to the session, when the save function is called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment