Created
April 24, 2012 08:49
-
-
Save jtallant/2478014 to your computer and use it in GitHub Desktop.
Amazon Cart With Classes
This file contains 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 Cart | |
def initialize | |
@the_cart = [] | |
end | |
def add(item, quantity) | |
@the_cart << { :item => item, :quantity => quantity } | |
end | |
def total | |
@the_cart.map{|i| i[:item].price * i[:quantity]}.inject(:+) | |
end | |
def list | |
list = "<ul>\n" | |
@the_cart.each do |i| | |
list += "<li>#{i[:item].name}: $#{i[:item].price} <span>(x#{i[:quantity]})</span></li>\n" | |
end | |
list += "</ul>\n" | |
end | |
end | |
class Item | |
attr_accessor :name, :price | |
def initialize(name, price) | |
@name = name | |
@price = price | |
end | |
end | |
ipad = Item.new("iPad 2", 499) | |
imac = Item.new("iMac 27", 1699) | |
macbook = Item.new("MacBook Air 13", 1299) | |
shopping_cart = Cart.new | |
shopping_cart.add(ipad, 2) | |
shopping_cart.add(imac, 1) | |
shopping_cart.add(macbook, 1) | |
puts shopping_cart.total # => 3996 | |
css = "<style>h1{text-align:center}#container{width:400px;margin:0 auto;}li{list-style-type:none;}h5{color:green}span{float:right;}</style>" | |
markup = "<h1>Your Cart</h1>\n<div id='container'>\n#{shopping_cart.list}<h5>Your Total: $#{shopping_cart.total}</h5>\n</div>" | |
afile = File.new("view_cart.html", "w") | |
output = "#{css}\n#{markup}" | |
afile.puts output | |
afile.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment