Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## line_item.rb
- class LineItem < ActiveRecord::Base
- belongs_to :product
- def self.for_product(product)
- item = self.new
- item.quantity = 1
- item.product = product
- item.unit_price = product.price
- end
- end
- ## product.rb
- class Product < ActiveRecord::Base
- validates_presence_of :title, :description, :image_url
- validates_numericality_of :price
- validates_uniqueness_of :title
- validates_format_of :image_url,
- :with => %r{\.(gif|jpg|png)$}i,
- :message => "must be a URL for a GIF, JPG or PNG image"
- protected
- def validate
- errors.add(:price, "should be positive") unless price.nil? || price>=0.01
- end
- # Return a list of products we can sell (which means they have to be
- # available). Show the most recent available first.
- def self.salable_items
- find( :all,
- :conditions => "date_available <= now()",
- :order => "date_available desc")
- end
- end
- ## cart.rb
- class Cart
- attr_reader :items
- attr_reader :total_price
- def initialize
- @items = []
- @total_price = 0.0
- end
- def add_product(product)
- @items << LineItem.for_product(product)
- @total_price += product.price
- end
- end
Add Comment
Please, Sign In to add comment