Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#to_procObject

Returns selected keys, named or renamed as specified myproduct = => “something”, :price => “20” liability = myproduct.tap(&=> :price) liability == 20 Note: Tap only works where source is a hash object, so use as otherwise (because tap always returns the object you are tapping) myproduct = ::OpenStruct.new(=> “something”, :price => “20”) liability.as!(&=> :price) liability == 20

Transforming values: Pass a hash as the value with the key being the source key/method myproduct = ::OpenStruct.new(=> “something”, :price => “20”) my_sale_product = myproduct.as!(&{:sale_price => {:price => ->(val){ val / 2 } } }) my_sale_product == 10



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/trax/core/ext/hash.rb', line 18

def to_proc
  ->(hash_or_object) {
    new_hash = {}

    if hash_or_object.is_a?(::Hash)
      self.each_pair do |k,v|
        if v.is_a?(Hash)
          new_hash[k] = v.values.first.call(hash_or_object[v.keys.first])
        elsif v.is_a?(Proc)
          new_hash[k] = v.call(hash_or_object[k])
        else
          new_hash[k] = hash_or_object[v]
        end
      end

      hash_or_object.keys.map{ |k| hash_or_object.delete(k) }
      hash_or_object.merge!(new_hash)
    else
      self.each_pair do |k,v|
        if v.is_a?(Hash)
          new_hash[k] = v.values.first.call(hash_or_object.__send__(v.keys.first))
        elsif v.is_a?(Proc)
          new_hash[k] = v.call(hash_or_object.__send__(k))
        else
          new_hash[k] = hash_or_object.__send__(v)
        end
      end
    end

    return new_hash
  }
end