Class: Hash

Inherits:
Object show all
Defined in:
lib/poolparty/core/hash.rb,
lib/poolparty/schema.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



70
71
72
73
74
75
76
77
78
# File 'lib/poolparty/schema.rb', line 70

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

#append(other_hash) ⇒ Object

TODO: deprecate def extract!(&block)

o = Hash[*select(&block).flatten]
o.keys.each {|k| self.delete(k) }
o

end



34
35
36
37
38
39
40
41
# File 'lib/poolparty/core/hash.rb', line 34

def append(other_hash)
  returning Hash.new do |h|
    h.merge!(self)
    other_hash.each do |k,v|
      h[k] = has_key?(k) ? [self[k], v].flatten.uniq : v
    end
  end
end

#append!(other_hash) ⇒ Object



43
44
45
46
47
48
# File 'lib/poolparty/core/hash.rb', line 43

def append!(other_hash)
  other_hash.each do |k,v|
    self[k] = has_key?(k) ? [self[k], v].flatten.uniq : v
  end
  self
end

#choose(&block) ⇒ Object



5
6
7
# File 'lib/poolparty/core/hash.rb', line 5

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

#next_sorted_key(from) ⇒ Object



64
65
66
67
# File 'lib/poolparty/core/hash.rb', line 64

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

#safe_merge(other_hash) ⇒ Object



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

def safe_merge(other_hash)
  merge(other_hash.delete_if {|k,v| has_key?(k) })
end

#safe_merge!(other_hash) ⇒ Object



54
55
56
# File 'lib/poolparty/core/hash.rb', line 54

def safe_merge!(other_hash)
  merge!(other_hash.delete_if {|k,v| has_key?(k) && !v.nil? })
end

#to_instance_variables(inst = nil) ⇒ Object



9
10
11
12
13
14
# File 'lib/poolparty/core/hash.rb', line 9

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

#to_osObject



58
59
60
61
62
# File 'lib/poolparty/core/hash.rb', line 58

def to_os
  m={}
  each {|k,v| m[k] = v.to_os }
  MyOpenStruct.new(m)
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"]


23
24
25
# File 'lib/poolparty/core/hash.rb', line 23

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