1class Product
2 include Comparable
3
4 attr_accessor :name, :price, :category
5 attr_reader :id, :created_at
6
7 @@count = 0
8
9 def initialize(name:, price:, category: :general)
10 @@count += 1
11 @id = @@count
12 @name = name
13 @price = price.to_f
14 @category = category
15 @created_at = Time.now
16 end
17
18 def <=>(other)
19 @price <=> other.price
20 end
21
22 def discounted(percent)
23 raise ArgumentError, "Invalid percent" unless (0..100).include?(percent)
24 new_price = @price * (1 - percent / 100.0)
25 self.class.new(name: @name, price: new_price, category: @category)
26 end
27
28 def to_h
29 {
30 id: @id,
31 name: @name,
32 price: @price,
33 category: @category,
34 created_at: @created_at.iso8601
35 }
36 end
37
38 def self.total_count
39 @@count
40 end
41
42 def self.bulk_discount(products, percent)
43 products.map { |p| p.discounted(percent) }
44 end
45
46 def to_s
47 "#<Product:#{@id} #{@name} $#{'%.2f' % @price}>"
48 end
49end