Module: DottedIndex

Defined in:
lib/rbot/core/utils/extends.rb

Overview

DottedIndex mixin: extend a Hash or Array class with this module to achieve [] and []= methods that automatically split indices at dots (indices are automatically converted to symbols, too)

You have to define the single_retrieve(key) and single_assign(key,value) methods (usually aliased at the original :[] and :[]= methods)

Instance Method Summary collapse

Instance Method Details

#[](*ar) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rbot/core/utils/extends.rb', line 55

def [](*ar)
  keys = self.rbot_index_split(ar)
  return self.single_retrieve(keys.first) if keys.length == 1
  h = self
  while keys.length > 1
    k = keys.shift
    h[k] ||= self.class.new
    h = h[k]
  end
  h[keys.last]
end

#[]=(*arr) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/rbot/core/utils/extends.rb', line 67

def []=(*arr)
  val = arr.last
  ar = arr[0..-2]
  keys = self.rbot_index_split(ar)
  return self.single_assign(keys.first, val) if keys.length == 1
  h = self
  while keys.length > 1
    k = keys.shift
    h[k] ||= self.class.new
    h = h[k]
  end
  h[keys.last] = val
end

#rbot_index_split(*ar) ⇒ Object



48
49
50
51
52
53
# File 'lib/rbot/core/utils/extends.rb', line 48

def rbot_index_split(*ar)
  keys = ([] << ar).flatten
  keys.map! { |k|
    k.to_s.split('.').map { |kk| kk.to_sym rescue nil }.compact
  }.flatten
end