Class: AwesomeO::Item

Inherits:
Object
  • Object
show all
Defined in:
lib/awesome_o/item.rb

Instance Method Summary collapse

Constructor Details

#initialize(item_id, cart_id, data) ⇒ Item

Returns a new instance of Item.



3
4
5
6
7
# File 'lib/awesome_o/item.rb', line 3

def initialize(item_id, cart_id, data)
  @id = item_id
  @cart_id = cart_id
  @data = data
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/awesome_o/item.rb', line 48

def method_missing(method, *args, &block)
  if method.to_s.end_with?('=')
    redis.hset _key, method[0..-2], args[0].to_s
    @data.store(method[0..-2].to_sym, args[0].to_s)
    version = touch
    @data.store(:_version, version)
  elsif @data.keys.include?(method)
    @data.fetch(method)
  else
    super
  end
end

Instance Method Details

#==(item) ⇒ Object



27
28
29
# File 'lib/awesome_o/item.rb', line 27

def ==(item)
  @id == item._id
end

#_idObject



9
10
11
# File 'lib/awesome_o/item.rb', line 9

def _id
  @id
end

#_keyObject



36
37
38
# File 'lib/awesome_o/item.rb', line 36

def _key
  "awesome_o:line_item:#{@id}"
end

#_versionObject



40
41
42
# File 'lib/awesome_o/item.rb', line 40

def _version
  super.to_i
end

#cache_keyObject



44
45
46
# File 'lib/awesome_o/item.rb', line 44

def cache_key
  "item/#{@id}-#{_version}"
end

#cartObject



19
20
21
# File 'lib/awesome_o/item.rb', line 19

def cart
  @cart ||= Cart.new(@cart_id)
end

#costObject



13
14
15
16
17
# File 'lib/awesome_o/item.rb', line 13

def cost
  unit_cost = (@data.fetch(AwesomeO.config.unit_cost_field).to_f * 100).to_i
  quantity = @data.fetch(AwesomeO.config.quantity_field).to_i
  (unit_cost * quantity) / 100.0
end

#destroyObject



23
24
25
# File 'lib/awesome_o/item.rb', line 23

def destroy
  cart.remove_item(self)
end

#respond_to_missing?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/awesome_o/item.rb', line 61

def respond_to_missing?(method, include_private = false)
  method.to_s.end_with?('=') || @data.keys.include?(method) || super
end

#touchObject



31
32
33
34
# File 'lib/awesome_o/item.rb', line 31

def touch
  cart.touch
  redis.hincrby _key, :_version, 1
end