Module: Transformers::Extensions::Hash
- Defined in:
- lib/transformers/extensions/hash.rb
Instance Method Summary collapse
- #convert(*keys) ⇒ Object
- #copy(key, options = {}) ⇒ Object
- #rename(key, options = {}) ⇒ Object
- #transform(key = nil, &block) ⇒ Object
Instance Method Details
#convert(*keys) ⇒ Object
12 13 14 15 16 17 18 19 20 |
# File 'lib/transformers/extensions/hash.rb', line 12 def convert(*keys) = keys. return unless keys.any? { |key| self.has_key?(key) } new_key = [:as] || keys.first converter = [:to] values = keys.collect { |key| delete(key) } new_value = converter ? Transformers.get(converter).call(*values) : (values.length == 1 ? values.first : values) self[new_key] = new_value end |
#copy(key, options = {}) ⇒ Object
28 29 30 31 32 |
# File 'lib/transformers/extensions/hash.rb', line 28 def copy(key, = {}) new_key = [:to] raise MissingOption.new(:to) if new_key.nil? self[new_key] = self[key] end |
#rename(key, options = {}) ⇒ Object
22 23 24 25 26 |
# File 'lib/transformers/extensions/hash.rb', line 22 def rename(key, = {}) new_key = [:to] raise MissingOption.new(:to) if new_key.nil? self[new_key] = self.delete(key) end |
#transform(key = nil, &block) ⇒ Object
4 5 6 7 8 9 10 |
# File 'lib/transformers/extensions/hash.rb', line 4 def transform(key = nil, &block) target = key.nil? ? self : self[key] if target raise TypeError.new("Can't apply transformations on #{target.inspect}. Expected a Hash") unless target.is_a?(Hash) target.instance_eval(&block) end end |