Module: NeoScout::HashDefaultsMixin

Included in:
HashWithDefault
Defined in:
lib/neoscout/tools.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/neoscout/tools.rb', line 100

def self.included(base)

  # defines map_value for mixin target baseclass instances and any subclass instances
  base.class_exec(base) do |base_class|
    define_method(:map_value) do |&blk|
      new_hash = {}
      each_pair do |k,v|
        new_hash[k] = if v.kind_of? base_class then v.map_value(&blk) else blk.call(v) end
      end
      new_hash
    end
  end

  # defines new_multi_keyed on the mixin's target baseclass
  # (subclasses the baseclass to override key_descr for instances)
  def base.new_multi_keyed(*list, &blk)
    new_class = Class.new(self)
    (class << new_class ; self end).class_exec(list.shift) do |descr|
      define_method(:key_descr) { || descr }
    end
    if list.empty?
      then new_class.new(&blk)
      else new_class.new { |key| self.new_multi_keyed(*list, &blk) } end
  end

end

Instance Method Details

#[](key) ⇒ Object



87
88
89
# File 'lib/neoscout/tools.rb', line 87

def [](key)
  if has_key?(key) then super(key) else self[key]=default(key) end
end

#default(key) ⇒ Object



83
84
85
# File 'lib/neoscout/tools.rb', line 83

def default(key)
  @default.call(key)
end

#initialize(*args, &blk) ⇒ Object



78
79
80
81
# File 'lib/neoscout/tools.rb', line 78

def initialize(*args, &blk)
  super *args
  @default = blk
end

#key_descrObject



95
96
97
# File 'lib/neoscout/tools.rb', line 95

def key_descr
  :key
end

#lookup(key, default_value = nil) ⇒ Object



91
92
93
# File 'lib/neoscout/tools.rb', line 91

def lookup(key, default_value = nil)
  if has_key?(key) then self[key] else self[key]=default_value end
end