Module: HashExtensions
- Included in:
- Hash
- Defined in:
- lib/trax/core/ext/hash.rb
Instance Method Summary collapse
- #assert_required_keys(*args) ⇒ Object
-
#to_transformer ⇒ Object
Returns selected keys, named or renamed as specified myproduct = => “something”, :price => “20” liability = myproduct.tap(&=> :price.to_transformer) 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.
Instance Method Details
#assert_required_keys(*args) ⇒ Object
2 3 4 5 6 |
# File 'lib/trax/core/ext/hash.rb', line 2 def assert_required_keys(*args) missing_args = args.reject{|arg| self.key?(arg) } raise ArgumentError.new("Missing keys: #{missing_args.join(', ')}") if missing_args.any? self end |
#to_transformer ⇒ Object
Returns selected keys, named or renamed as specified myproduct = => “something”, :price => “20” liability = myproduct.tap(&=> :price.to_transformer) 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
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 50 51 52 53 54 55 |
# File 'lib/trax/core/ext/hash.rb', line 24 def to_transformer ->(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 |