Class: Map

Inherits:
Hash
  • Object
show all
Defined in:
lib/map.rb,
lib/map/struct.rb,
lib/map/options.rb

Defined Under Namespace

Modules: Arguments, Options Classes: Struct

Constant Summary collapse

Version =
'2.7.0'
Load =
Kernel.method(:load)
Dynamic =
lambda do
  conversion_methods.reverse_each do |method|
    add_conversion_method!(method)
  end
end
Dup =
instance_method(:dup)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args, &block) ⇒ Map

Returns a new instance of Map.



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/map.rb', line 168

def initialize(*args, &block)
  case args.size
    when 0
      super(&block)

    when 1
      first = args.first
      case first
        when Hash
          initialize_from_hash(first)
        when Array
          initialize_from_array(first)
        else
          if first.respond_to?(:to_hash)
            initialize_from_hash(first.to_hash)
          else
            initialize_from_hash(first)
          end
      end

    else
      initialize_from_array(args)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object

a sane method missing that only supports writing values or reading *previously set* values



561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'lib/map.rb', line 561

def method_missing(*args, &block)
  method = args.first.to_s
  case method
    when /=$/
      key = args.shift.to_s.chomp('=')
      value = args.shift
      self[key] = value
    else
      key = method
      unless has_key?(key)
        return(block ? fetch(*args, &block) : super(*args))
      end
      self[key]
  end
end

Class Method Details

.add_conversion_method!(method) ⇒ Object

Raises:

  • (ArguementError)


70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/map.rb', line 70

def add_conversion_method!(method)
  method = method.to_s.strip
  raise ArguementError if method.empty?
  module_eval(<<-__, __FILE__, __LINE__)
    unless public_method_defined?(#{ method.inspect })
      def #{ method }
        self
      end
    end
    unless conversion_methods.include?(#{ method.inspect })
      conversion_methods.unshift(#{ method.inspect })
    end
  __
end

.allocateObject



28
29
30
31
32
33
# File 'lib/map.rb', line 28

def allocate
  super.instance_eval do
    @keys = []
    self
  end
end

.alphanumeric_key_for(key) ⇒ Object



691
692
693
694
# File 'lib/map.rb', line 691

def Map.alphanumeric_key_for(key)
  return key if Numeric===key
  key.to_s =~ %r/^\d+$/ ? Integer(key) : key
end

.blank?(value) ⇒ Boolean

Returns:

  • (Boolean)


616
617
618
619
620
621
622
623
624
625
626
627
628
629
# File 'lib/map.rb', line 616

def Map.blank?(value)
  return value.blank? if value.respond_to?(:blank?)

  case value
    when String
      value.strip.empty?
    when Numeric
      value == 0
    when false
      true
    else
      value.respond_to?(:empty?) ? value.empty? : !value
  end
end

.coerce(other) ⇒ Object



49
50
51
52
53
54
55
56
# File 'lib/map.rb', line 49

def coerce(other)
  case other
    when Map
      other
    else
      allocate.update(other.to_hash)
  end
end

.conversion_methodsObject



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/map.rb', line 58

def conversion_methods
  @conversion_methods ||= (
    map_like = ancestors.select{|ancestor| ancestor <= Map}
    type_names = map_like.map do |ancestor|
      name = ancestor.name.to_s.strip
      next if name.empty?
      name.downcase.gsub(/::/, '_')
    end.compact
    type_names.map{|type_name| "to_#{ type_name }"}
  )
end

.convert_key(key) ⇒ Object



219
220
221
# File 'lib/map.rb', line 219

def self.convert_key(key)
  key.kind_of?(Symbol) ? key.to_s : key
end

.convert_value(value) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/map.rb', line 230

def self.convert_value(value)
  conversion_methods.each do |method|
    #return convert_value(value.send(method)) if value.respond_to?(method)
    if value.respond_to?(method)
      value = value.send(method)
      break
    end
  end

  case value
    when Hash
      coerce(value)
    when Array
      value.map{|v| convert_value(v)}
    else
      value
  end
end

.depth_first_each(enumerable, path = [], accum = [], &block) ⇒ Object



700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
# File 'lib/map.rb', line 700

def Map.depth_first_each(enumerable, path = [], accum = [], &block)
  Map.pairs_for(enumerable) do |key, val|
    path.push(key)
    if((val.is_a?(Hash) or val.is_a?(Array)) and not val.empty?)
      Map.depth_first_each(val, path, accum)
    else
      accum << [path.dup, val]
    end
    path.pop()
  end
  if block
    accum.each{|keys, val| block.call(keys, val)}
  else
    [path, accum]
  end
end

.each_pair(*args, &block) ⇒ Object

iterate over arguments in pairs smartly.



92
93
94
95
96
97
98
99
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/map.rb', line 92

def each_pair(*args, &block)
  size = args.size
  parity = size % 2 == 0 ? :even : :odd
  first = args.first

  if block.nil?
    result = []
    block = lambda{|*kv| result.push(kv)}
  else
    result = args
  end

  return args if size == 0

  if size == 1
    conversion_methods.each do |method|
      if first.respond_to?(method)
        first = first.send(method)
        break
      end
    end

    if first.respond_to?(:each_pair)
      first.each_pair do |key, val|
        block.call(key, val)
      end
      return args
    end

    if first.respond_to?(:each_slice)
      first.each_slice(2) do |key, val|
        block.call(key, val)
      end
      return args
    end

    raise(ArgumentError, 'odd number of arguments for Map')
  end

  array_of_pairs = args.all?{|a| a.is_a?(Array) and a.size == 2}

  if array_of_pairs
    args.each do |pair|
      key, val, *ignored = pair
      block.call(key, val)
    end
  else
    0.step(args.size - 1, 2) do |a|
      key = args[a]
      val = args[a + 1]
      block.call(key, val)
    end
  end

  args
end

.for(*args, &block) ⇒ Object



42
43
44
45
46
47
# File 'lib/map.rb', line 42

def for(*args, &block)
  if(args.size == 1 and block.nil?)
    return args.first if args.first.class == self
  end
  new(*args, &block)
end

.inherited(other) ⇒ Object



85
86
87
88
# File 'lib/map.rb', line 85

def inherited(other)
  other.module_eval(&Dynamic)
  super
end

.libdir(*args, &block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/map.rb', line 10

def libdir(*args, &block)
  @libdir ||= File.expand_path(__FILE__).sub(/\.rb$/,'')
  libdir = args.empty? ? @libdir : File.join(@libdir, *args.map{|arg| arg.to_s})
ensure
  if block
    begin
      $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.first==libdir
      module_eval(&block)
    ensure
      $LOAD_PATH.shift() if $LOAD_PATH.first==libdir
    end
  end
end

.load(*args, &block) ⇒ Object



24
25
26
# File 'lib/map.rb', line 24

def load(*args, &block)
  libdir{ Load.call(*args, &block) }
end

.map_for(hash) ⇒ Object



210
211
212
213
214
# File 'lib/map.rb', line 210

def Map.map_for(hash)
  map = klass.coerce(hash)
  map.default = hash.default
  map
end

.new(*args, &block) ⇒ Object Also known as: []



35
36
37
38
39
40
# File 'lib/map.rb', line 35

def new(*args, &block)
  allocate.instance_eval do
    initialize(*args, &block)
    self
  end
end

.options_for(*args, &block) ⇒ Object



145
146
147
# File 'lib/map/options.rb', line 145

def Map.options_for(*args, &block)
  Map::Options.for(*args, &block)
end

.options_for!(*args, &block) ⇒ Object



149
150
151
# File 'lib/map/options.rb', line 149

def Map.options_for!(*args, &block)
  Map::Options.for(*args, &block).pop
end

.pairs_for(enumerable, *args, &block) ⇒ Object



717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'lib/map.rb', line 717

def Map.pairs_for(enumerable, *args, &block)
  if block.nil?
    pairs, block = [], lambda{|*pair| pairs.push(pair)}
  else
    pairs = false
  end

  result =
    case enumerable
      when Hash
        enumerable.each_pair(*args, &block)
      when Array
        enumerable.each_with_index(*args) do |val, key|
          block.call(key, val)
        end
      else
        enumerable.each_pair(*args, &block)
    end

  pairs ? pairs : result
end

.struct(*args, &block) ⇒ Object



45
46
47
# File 'lib/map/struct.rb', line 45

def Map.struct(*args, &block)
  new(*args, &block).struct
end

.versionObject



6
7
8
# File 'lib/map.rb', line 6

def version
  Map::Version
end

Instance Method Details

#<=>(other) ⇒ Object



454
455
456
# File 'lib/map.rb', line 454

def <=>(other)
  keys <=> klass.coerce(other).keys
end

#==(hash) ⇒ Object

misc



448
449
450
451
452
# File 'lib/map.rb', line 448

def ==(hash)
  return false unless(Map === hash)
  return false if keys != hash.keys
  super hash
end

#=~(hash) ⇒ Object



458
459
460
# File 'lib/map.rb', line 458

def =~(hash)
  to_hash == klass.coerce(hash).to_hash
end

#[](key) ⇒ Object



302
303
304
# File 'lib/map.rb', line 302

def [](key)
  __get__(convert_key(key))
end

#[]=(key, val) ⇒ Object Also known as: store



295
296
297
298
299
# File 'lib/map.rb', line 295

def []=(key, val)
  key, val = convert(key, val)
  keys.push(key) unless has_key?(key)
  __set__(key, val)
end

#__get__Object



292
# File 'lib/map.rb', line 292

alias_method '__get__', '[]'

#__set__Object

writer/reader methods



291
# File 'lib/map.rb', line 291

alias_method '__set__', '[]='

#__update__Object



293
# File 'lib/map.rb', line 293

alias_method '__update__', 'update'

#alphanumeric_key_for(key) ⇒ Object



696
697
698
# File 'lib/map.rb', line 696

def alphanumeric_key_for(key)
  Map.alphanumeric_key_for(key)
end

#apply(other) ⇒ Object



684
685
686
687
688
689
# File 'lib/map.rb', line 684

def apply(other)
  Map.for(other).depth_first_each do |keys, value|
    set(keys => value) unless !get(keys).nil?
  end
  self
end

#as_hashObject



513
514
515
516
517
518
# File 'lib/map.rb', line 513

def as_hash
  @class = Hash
  yield
ensure
  @class = nil
end

#blank?(*keys) ⇒ Boolean

Returns:

  • (Boolean)


611
612
613
614
# File 'lib/map.rb', line 611

def blank?(*keys)
  return empty? if keys.empty?
  !has?(*keys) or Map.blank?(get(*keys))
end

#classObject



520
521
522
# File 'lib/map.rb', line 520

def class
  @class || super
end

#clearObject



387
388
389
390
# File 'lib/map.rb', line 387

def clear
  keys.clear
  super
end

#cloneObject



281
282
283
# File 'lib/map.rb', line 281

def clone
  copy
end

#collection_has_key?(collection, key) ⇒ Boolean

Returns:

  • (Boolean)


631
632
633
634
635
636
637
638
639
# File 'lib/map.rb', line 631

def collection_has_key?(collection, key)
  case collection
    when Hash
      collection.has_key?(key)
    when Array
      return false unless key
      (0...collection.size).include?(Integer(key))
  end
end

#conversion_methodsObject

conversions



492
493
494
# File 'lib/map.rb', line 492

def conversion_methods
  self.class.conversion_methods
end

#convert(key, val) ⇒ Object



257
258
259
# File 'lib/map.rb', line 257

def convert(key, val)
  [convert_key(key), convert_value(val)]
end

#convert_key(key) ⇒ Object



222
223
224
225
226
227
228
# File 'lib/map.rb', line 222

def convert_key(key)
  if klass.respond_to?(:convert_key)
    klass.convert_key(key)
  else
    Map.convert_key(key)
  end
end

#convert_value(value) ⇒ Object Also known as: convert_val



248
249
250
251
252
253
254
# File 'lib/map.rb', line 248

def convert_value(value)
  if klass.respond_to?(:convert_value)
    klass.convert_value(value)
  else
    Map.convert_value(value)
  end
end

#copyObject

maps are aggressive with copy operations. they are all deep copies. make a new one if you really want a shallow copy

TODO - fallback to shallow if objects cannot be marshal’d.…



265
266
267
268
269
270
271
272
273
# File 'lib/map.rb', line 265

def copy
  default = self.default
  self.default = nil
  copy = Marshal.load(Marshal.dump(self)) rescue Dup.bind(self).call()
  copy.default = default
  copy
ensure
  self.default = default
end

#default(key = nil) ⇒ Object



285
286
287
# File 'lib/map.rb', line 285

def default(key = nil)
  key.is_a?(Symbol) && include?(key = key.to_s) ? self[key] : super
end

#delete(key) ⇒ Object

mutators



381
382
383
384
385
# File 'lib/map.rb', line 381

def delete(key)
  key = convert_key(key)
  keys.delete(key)
  super(key)
end

#delete_ifObject



392
393
394
395
396
397
# File 'lib/map.rb', line 392

def delete_if
  to_delete = []
  keys.each{|key| to_delete.push(key) if yield(key)}
  to_delete.each{|key| delete(key)}
  self
end

#depth_first_each(*args, &block) ⇒ Object



739
740
741
# File 'lib/map.rb', line 739

def depth_first_each(*args, &block)
  Map.depth_first_each(enumerable=self, *args, &block)
end

#dupObject



277
278
279
# File 'lib/map.rb', line 277

def dup
  copy
end

#eachObject Also known as: each_pair



373
374
375
376
# File 'lib/map.rb', line 373

def each
  keys.each{|key| yield(key, self[key])}
  self
end

#each_keyObject



363
364
365
366
# File 'lib/map.rb', line 363

def each_key
  keys.each{|key| yield(key)}
  self
end

#each_valueObject



368
369
370
371
# File 'lib/map.rb', line 368

def each_value
  keys.each{|key| yield self[key]}
  self
end

#each_with_indexObject

iterator methods



358
359
360
361
# File 'lib/map.rb', line 358

def each_with_index
  keys.each_with_index{|key, index| yield([key, self[key]], index)}
  self
end

#fetch(key, *args, &block) ⇒ Object



306
307
308
# File 'lib/map.rb', line 306

def fetch(key, *args, &block)
  super(convert_key(key), *args, &block)
end

#firstObject



348
349
350
# File 'lib/map.rb', line 348

def first
  [keys.first, self[keys.first]]
end

#get(*keys) ⇒ Object

support for compound key indexing and depth first iteration



584
585
586
587
588
589
590
591
592
593
594
595
# File 'lib/map.rb', line 584

def get(*keys)
  keys = keys.flatten
  return self[keys.first] if keys.size <= 1
  keys, key = keys[0..-2], keys[-1]
  collection = self
  keys.each do |k|
    k = alphanumeric_key_for(k)
    collection = collection[k]
    return collection unless collection.respond_to?('[]')
  end
  collection[alphanumeric_key_for(key)]
end

#has?(*keys) ⇒ Boolean

Returns:

  • (Boolean)


597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/map.rb', line 597

def has?(*keys)
  keys = keys.flatten
  collection = self
  return collection_has_key?(collection, keys.first) if keys.size <= 1
  keys, key = keys[0..-2], keys[-1]
  keys.each do |k|
    k = alphanumeric_key_for(k)
    collection = collection[k]
    return collection unless collection.respond_to?('[]')
  end
  return false unless(collection.is_a?(Hash) or collection.is_a?(Array))
  collection_has_key?(collection, alphanumeric_key_for(key))
end

#idObject

Raises:

  • (NoMethodError)


577
578
579
580
# File 'lib/map.rb', line 577

def id
  raise NoMethodError unless has_key?(:id)
  self[:id]
end

#initialize_from_array(array) ⇒ Object



199
200
201
202
# File 'lib/map.rb', line 199

def initialize_from_array(array)
  map = self
  Map.each_pair(array){|key, val| map[key] = val}
end

#initialize_from_hash(hash) ⇒ Object



193
194
195
196
197
# File 'lib/map.rb', line 193

def initialize_from_hash(hash)
  map = self
  map.update(hash)
  map.default = hash.default
end

#inspectObject



484
485
486
487
488
# File 'lib/map.rb', line 484

def inspect
  array = []
  each{|key, val| array << (key.inspect + "=>" + val.inspect)}
  string = '{' + array.join(", ") + '}'
end

#invertObject



462
463
464
465
466
467
# File 'lib/map.rb', line 462

def invert
  inverted = klass.allocate
  inverted.default = self.default
  keys.each{|key| inverted[self[key]] = key }
  inverted
end

#key?(key) ⇒ Boolean Also known as: include?, has_key?, member?

Returns:

  • (Boolean)


310
311
312
# File 'lib/map.rb', line 310

def key?(key)
  super(convert_key(key))
end

#keysObject

instance constructor



164
165
166
# File 'lib/map.rb', line 164

def keys
  @keys ||= []
end

#klassObject

support methods



206
207
208
# File 'lib/map.rb', line 206

def klass
  self.class
end

#lastObject



352
353
354
# File 'lib/map.rb', line 352

def last
  [keys.last, self[keys.last]]
end

#map_for(hash) ⇒ Object



215
216
217
# File 'lib/map.rb', line 215

def map_for(hash)
  klass.map_for(hash)
end

#merge(*args) ⇒ Object



323
324
325
# File 'lib/map.rb', line 323

def merge(*args)
  copy.update(*args)
end

#popObject



438
439
440
441
442
443
444
# File 'lib/map.rb', line 438

def pop
  unless empty?
    key = keys.last
    val = delete(key)
    [key, val]
  end
end

#push(*args) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
# File 'lib/map.rb', line 426

def push(*args)
  Map.each_pair(*args) do |key, val|
    if key?(key)
      delete(key)
    else
      keys.push(key)
    end
    __set__(key, val)
  end
  self
end

#reject(&block) ⇒ Object



469
470
471
# File 'lib/map.rb', line 469

def reject(&block)
  dup.delete_if(&block)
end

#reject!(&block) ⇒ Object



473
474
475
476
# File 'lib/map.rb', line 473

def reject!(&block)
  hash = reject(&block)
  self == hash ? nil : hash
end

#replace(*args) ⇒ Object



399
400
401
402
# File 'lib/map.rb', line 399

def replace(*args)
  clear
  update(*args)
end

#reverse_merge(hash) ⇒ Object



327
328
329
330
331
# File 'lib/map.rb', line 327

def reverse_merge(hash)
  map = copy
  hash.each{|key, val| map[key] = val unless map.key?(key)}
  map
end

#reverse_merge!(hash) ⇒ Object



333
334
335
# File 'lib/map.rb', line 333

def reverse_merge!(hash)
  replace(reverse_merge(hash))
end

#selectObject



478
479
480
481
482
# File 'lib/map.rb', line 478

def select
  array = []
  each{|key, val| array << [key,val] if yield(key, val)}
  array
end

#set(*args) ⇒ Object



641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
# File 'lib/map.rb', line 641

def set(*args)
  if args.size == 1 and args.first.is_a?(Hash)
    options = args.shift
  else
    options = {}
    value = args.pop
    keys = args
    options[keys] = value
  end

  options.each do |keys, value|
    keys = Array(keys).flatten

    collection = self
    if keys.size <= 1
      collection[keys.first] = value
      next
    end

    key = nil

    keys.each_cons(2) do |a, b|
      a, b = alphanumeric_key_for(a), alphanumeric_key_for(b)

      case b
        when Numeric
          collection[a] ||= []
          raise(IndexError, "(#{ collection.inspect })[#{ a.inspect }]=#{ value.inspect }") unless collection[a].is_a?(Array)

        when String, Symbol
          collection[a] ||= {}
          raise(IndexError, "(#{ collection.inspect })[#{ a.inspect }]=#{ value.inspect }") unless collection[a].is_a?(Hash)
      end
      collection = collection[a]
      key = b
    end

    collection[key] = value
  end

  return options.values
end

#shiftObject

ordered container specific methods



406
407
408
409
410
411
412
# File 'lib/map.rb', line 406

def shift
  unless empty?
    key = keys.first
    val = delete(key)
    [key, val]
  end
end

#stringify_keysObject



550
# File 'lib/map.rb', line 550

def stringify_keys; dup end

#stringify_keys!Object

oh rails - would that map.rb existed before all this non-sense…



549
# File 'lib/map.rb', line 549

def stringify_keys!; self end

#structObject



41
42
43
# File 'lib/map/struct.rb', line 41

def struct
  @struct ||= Struct.new(map=self)
end

#symbolize_keysObject



552
# File 'lib/map.rb', line 552

def symbolize_keys; dup end

#symbolize_keys!Object



551
# File 'lib/map.rb', line 551

def symbolize_keys!; self end

#to_arrayObject Also known as: to_a



528
529
530
531
532
# File 'lib/map.rb', line 528

def to_array
  array = []
  each{|*pair| array.push(pair)}
  array
end

#to_hashObject



504
505
506
507
508
509
510
511
# File 'lib/map.rb', line 504

def to_hash
  hash = Hash.new(default)
  each do |key, val|
    val = val.to_hash if val.respond_to?(:to_hash)
    hash[key] = val
  end
  hash
end

#to_listObject



535
536
537
538
539
540
541
# File 'lib/map.rb', line 535

def to_list
  list = []
  each_pair do |key, val|
    list[key.to_i] = val if(key.is_a?(Numeric) or key.to_s =~ %r/^\d+$/)
  end
  list
end

#to_optionsObject



554
# File 'lib/map.rb', line 554

def to_options; dup end

#to_options!Object



553
# File 'lib/map.rb', line 553

def to_options!; self end

#to_sObject



543
544
545
# File 'lib/map.rb', line 543

def to_s
  to_array.to_s
end

#to_yaml(*args, &block) ⇒ Object



524
525
526
# File 'lib/map.rb', line 524

def to_yaml(*args, &block)
  as_hash{ super }
end

#unshift(*args) ⇒ Object



414
415
416
417
418
419
420
421
422
423
424
# File 'lib/map.rb', line 414

def unshift(*args)
  Map.each_pair(*args) do |key, val|
    if key?(key)
      delete(key)
    else
      keys.unshift(key)
    end
    __set__(key, val)
  end
  self
end

#update(*args) ⇒ Object Also known as: merge!



317
318
319
320
# File 'lib/map.rb', line 317

def update(*args)
  Map.each_pair(*args){|key, val| store(key, val)}
  self
end

#valuesObject Also known as: vals



337
338
339
340
341
# File 'lib/map.rb', line 337

def values
  array = []
  keys.each{|key| array.push(self[key])}
  array
end

#values_at(*keys) ⇒ Object



344
345
346
# File 'lib/map.rb', line 344

def values_at(*keys)
  keys.map{|key| self[key]}
end

#with_indifferent_accessObject



556
# File 'lib/map.rb', line 556

def with_indifferent_access; dup end

#with_indifferent_access!Object



555
# File 'lib/map.rb', line 555

def with_indifferent_access!; self end