Class: Volt::GenericPool

Inherits:
Object show all
Defined in:
lib/volt/utils/generic_pool.rb

Overview

GenericPool is a base class you can inherit from to cache items based on a lookup.

GenericPool assumes either a block is passed to lookup, or a #create method, that takes the path arguments and reutrns a new instance.

GenericPool can handle as deep of paths as needed. You can also lookup all of the items at a sub-path with #lookup_all

TODO: make the lookup/create threadsafe

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGenericPool

Returns a new instance of GenericPool.



15
16
17
# File 'lib/volt/utils/generic_pool.rb', line 15

def initialize
  @pool = {}
end

Instance Attribute Details

#poolObject (readonly)

Returns the value of attribute pool.



13
14
15
# File 'lib/volt/utils/generic_pool.rb', line 13

def pool
  @pool
end

Instance Method Details

#create_new_item(*args) ⇒ Object

Does the actual creating, if a block is not passed in, it calls #create on the class.



43
44
45
46
47
48
49
50
51
# File 'lib/volt/utils/generic_pool.rb', line 43

def create_new_item(*args)
  if block_given?
    new_item = yield(*args)
  else
    new_item = create(*args)
  end

  transform_item(new_item)
end

#lookup(*args, &block) ⇒ Object Also known as: __lookup



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/volt/utils/generic_pool.rb', line 19

def lookup(*args, &block)
  section = @pool

  # TODO: This is to work around opal issue #500
  if RUBY_PLATFORM == 'opal'
    args.pop if args.last.nil?
  end

  args.each_with_index do |arg, index|
    last = (args.size - 1) == index

    if last
      # return, creating if needed
      return(section[arg] ||= create_new_item(*args, &block))
    else
      next_section = section[arg]
      next_section ||= (section[arg] = {})
      section      = next_section
    end
  end
end

#lookup_all(*args) ⇒ Object



62
63
64
65
66
67
68
69
70
# File 'lib/volt/utils/generic_pool.rb', line 62

def lookup_all(*args)
  result = __lookup(*args) { nil }

  if result
    return result.values
  else
    return []
  end
end

#remove(*args) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/volt/utils/generic_pool.rb', line 72

def remove(*args)
  stack   = []
  section = @pool

  args.each_with_index do |arg, index|
    stack << section

    if args.size - 1 == index
      section.delete(arg)
    else
      section = section[arg]
    end
  end

  (stack.size - 1).downto(1) do |index|
    node   = stack[index]
    parent = stack[index - 1]

    if node.size == 0
      parent.delete(args[index - 1])
    end
  end
end

#transform_item(item) ⇒ Object

Allow other pools to override how the created item gets stored.



54
55
56
# File 'lib/volt/utils/generic_pool.rb', line 54

def transform_item(item)
  item
end