Skip to content

Instantly share code, notes, and snippets.

/cart.rb Secret

Created August 23, 2016 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/269e34a551d977bda247e2dbaf3fb40a to your computer and use it in GitHub Desktop.
Save anonymous/269e34a551d977bda247e2dbaf3fb40a to your computer and use it in GitHub Desktop.
require 'sinatra'
enable :sessions
@@products = {
1 => {name: "Lotion", price: 9.99, weight: 4},
2 => {name: "Bar Soap", price: 4.99, weight: 4},
3 => {name: "Liquid Soap", price: 7.99, weight: 4}
}
get '/cart' do
product_id = params[:product_id]
action = params[:action]
session[:cart] ||= {}
case action
when 'add'
if @@products[product_id]
unless session[:cart].key?(product_id)
session[:cart][product_id] = 0
end
session[:cart][product_id] += 1
end
when 'update'
if params[:quantity].is_a?(Hash)
params[:quantity].each do |product_id, quantity|
if @@products[product_id] && session[:cart].key?(product_id)
session[:cart][product_id] = quantity
end
end
end
when 'remove'
if session[:cart].key?(product_id)
session[:cart].delete(product_id)
end
end
session[:cart].inspect
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment