Last active
August 29, 2015 14:22
-
-
Save solnic/985414e46b09d6309921 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'rom' | |
| require 'transproc' | |
| module Transformations | |
| extend Transproc::Functions | |
| def eval_keys(hash, param) | |
| hash.each_with_object(Hash[hash]) do |(key, value), copy| | |
| copy[key] = | |
| case value | |
| when Proc then value.call(param) | |
| when Hash then eval_keys(value, param) | |
| when Array then value.map { |v| eval_keys(v, param) } | |
| else value | |
| end | |
| end | |
| end | |
| end | |
| class Mapper < ROM::Mapper | |
| reject_keys true | |
| attribute :name | |
| attribute :foo_id, from: :foo_key do |value| | |
| proc { |resolver| resolver.foo_id(value) } | |
| end | |
| end | |
| class Resolver | |
| def self.foo_id(key) | |
| { 'FOO' => 123, 'BAR' => 321 }.fetch(key) | |
| end | |
| end | |
| input = [ | |
| { | |
| name: 'Jane', | |
| foo_key: 'FOO' | |
| }, | |
| { | |
| name: 'John', | |
| foo_key: 'BAR' | |
| } | |
| ] | |
| mapper = Mapper.build | |
| output = mapper.call(input) | |
| evaled = output.map { |el| Transproc(:eval_keys, Resolver).call(el) } | |
| puts evaled.inspect | |
| # [{:name=>"Jane", :foo_id=>123}, {:name=>"John", :foo_id=>321}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment