Guest User

Untitled

a guest
Feb 21st, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. ## line_item.rb
  2.  
  3. class LineItem < ActiveRecord::Base
  4. belongs_to :product
  5. def self.for_product(product)
  6. item = self.new
  7. item.quantity = 1
  8. item.product = product
  9. item.unit_price = product.price
  10. end
  11. end
  12.  
  13.  
  14.  
  15. ## product.rb
  16. class Product < ActiveRecord::Base
  17. validates_presence_of :title, :description, :image_url
  18. validates_numericality_of :price
  19. validates_uniqueness_of :title
  20. validates_format_of :image_url,
  21. :with => %r{\.(gif|jpg|png)$}i,
  22. :message => "must be a URL for a GIF, JPG or PNG image"
  23.  
  24. protected
  25. def validate
  26. errors.add(:price, "should be positive") unless price.nil? || price>=0.01
  27. end
  28.  
  29. # Return a list of products we can sell (which means they have to be
  30. # available). Show the most recent available first.
  31. def self.salable_items
  32. find( :all,
  33. :conditions => "date_available <= now()",
  34. :order => "date_available desc")
  35. end
  36. end
  37.  
  38. ## cart.rb
  39. class Cart
  40. attr_reader :items
  41. attr_reader :total_price
  42.  
  43. def initialize
  44. @items = []
  45. @total_price = 0.0
  46. end
  47. def add_product(product)
  48. @items << LineItem.for_product(product)
  49. @total_price += product.price
  50. end
  51. end
Add Comment
Please, Sign In to add comment