Class: 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.



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

def initialize
  @pool = {}
end

Instance Attribute Details

#poolObject (readonly)

Returns the value of attribute pool.



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

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.



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

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

  return transform_item(new_item)
end

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



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

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



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

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

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

#remove(*args) ⇒ Object



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

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.



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

def transform_item(item)
  item
end