Class: Hash

Inherits:
Object show all
Defined in:
lib/core/hash.rb

Overview

Hash extentions

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object



71
72
73
74
75
76
77
78
79
# File 'lib/core/hash.rb', line 71

def method_missing(sym, *args, &block)
  if has_key?(sym.to_sym)
    fetch(sym)
  elsif has_key?(sym.to_s)
    fetch(sym.to_s)
  else
    super
  end
end

Instance Method Details

#choose(&block) ⇒ Object

Return a hash of all the elements where the block evaluates to true



7
8
9
# File 'lib/core/hash.rb', line 7

def choose(&block)
  Hash[*self.select(&block).inject([]){|res,(k,v)| res << k << v}]
end

#next_sorted_key(from) ⇒ Object



29
30
31
32
# File 'lib/core/hash.rb', line 29

def next_sorted_key(from)
  idx = (size - keys.sort.index(from))
  keys.sort[idx - 1]
end

#stringify_keysObject



34
35
36
# File 'lib/core/hash.rb', line 34

def stringify_keys
  dup.stringify_keys!
end

#stringify_keys!Object

Converts all of the keys to strings



39
40
41
42
43
44
45
46
47
# File 'lib/core/hash.rb', line 39

def stringify_keys!
  keys.each{|k| 
    v = delete(k)
    self[k.to_s] = v
    v.stringify_keys! if v.is_a?(Hash)
    v.each{|p| p.stringify_keys! if p.is_a?(Hash)} if v.is_a?(Array)
  }
  self
end

#symbolize_keys(key_modifier = nil) ⇒ Object



49
50
51
# File 'lib/core/hash.rb', line 49

def symbolize_keys(key_modifier=nil)
  dup.symbolize_keys!(key_modifier)
end

#symbolize_keys!(key_modifier = nil) ⇒ Object

Converts all of the keys to strings can pass in a :key_modifier that will be sent to each key, before being symbolized. This can be usefull if you want to downcase, or snake_case each key. >> => {‘AvailabilityZone’=>“us-east-1a” }.symbolize_keys(:snake_case)

> :placement=>{:availability_zone=>“us-east-1a”}



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

def symbolize_keys!(key_modifier=nil) 
  keys.each{|k| 
    v = delete(k)
    if key_modifier && k.respond_to?(key_modifier)
      k = k.send(key_modifier)
    end
    self[k.to_sym] = v
    v.symbolize_keys!(key_modifier) if v.is_a?(Hash)
    v.each{|p| p.symbolize_keys!(key_modifier) if p.is_a?(Hash)} if v.is_a?(Array)
  }
  self
end

#to_instance_variables(inst = nil) ⇒ Object



11
12
13
14
15
16
# File 'lib/core/hash.rb', line 11

def to_instance_variables(inst=nil)
  each do |k,v|
    inst.instance_variable_set "@#{k}", v
    inst.class.send :attr_reader, k if inst
  end
end

#values_at(*indices) ⇒ Object

extracted from activesupport Returns an array of the values at the specified indices:

hash = HashWithIndifferentAccess.new
hash[:a] = "x"
hash[:b] = "y"
hash.values_at("a", "b") # => ["x", "y"]


25
26
27
# File 'lib/core/hash.rb', line 25

def values_at(*indices)
  indices.collect {|key| self[key]}.compact
end