Module: DataTransformer
- Defined in:
- lib/data_transformer.rb,
lib/data_transformer/version.rb
Constant Summary collapse
- VERSION =
"1.0.0"
Class Attribute Summary collapse
-
.tracing ⇒ Object
enable debug tracing.
Class Method Summary collapse
-
.all(collection, rules) ⇒ Object
Transforms collection of objects according to rules.
- .apply_rule(obj, rule) ⇒ Object
- .apply_rules(object, rules) ⇒ Object
-
.one(obj, rules) ⇒ Object
Transform Object to Hash according to rules.
Class Attribute Details
.tracing ⇒ Object
enable debug tracing
5 6 7 |
# File 'lib/data_transformer.rb', line 5 def tracing @tracing end |
Class Method Details
.all(collection, rules) ⇒ Object
Transforms collection of objects according to rules. See rule examples in docs for DataTransformer#one
32 33 34 |
# File 'lib/data_transformer.rb', line 32 def all(collection, rules) collection.map{|x| one(x, rules)} end |
.apply_rule(obj, rule) ⇒ Object
36 37 38 |
# File 'lib/data_transformer.rb', line 36 def apply_rule(obj, rule) apply_rules obj, Array(rule) end |
.apply_rules(object, rules) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/data_transformer.rb', line 40 def apply_rules(object, rules) rules.reduce(object) do |obj, rule| p [obj, rule] if tracing case rule when Array obj.map{|x| apply_rules(x, rule)} when Symbol obj.send(rule) when Proc rule.(obj) when Hash rule.reduce({}) do |result, (k,v)| result.merge({k => apply_rule(obj, v)}) end else raise ArgumentError, 'Only Symbol, Proc and Array or Hash of above are supported.' end end end |
.one(obj, rules) ⇒ Object
Transform Object to Hash according to rules. Rules is an array of elements of following type :foo => x.foo :bar => x.bar [:bar] => x.map(&:bar) [:bar :baz] => x.bar.baz [:bar [:baz]] => x.bar.map(&:baz) [:bar [:baz :quux]] => x.bar.map{|y| y.baz.quux}
15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/data_transformer.rb', line 15 def one(obj, rules) rules.reduce({}) do |results,rule| case rule when Symbol results.merge(rule => apply_rule(obj, rule)) when Hash ((key, value),) = rule.to_a results.merge(key => apply_rule(obj, value)) else raise ArgumentError, 'Only Symbol and Hash (with Symbols or Arrays) are supported as toplevel rules.' end end end |