Skip to content

Instantly share code, notes, and snippets.

@jmhodges
Created September 4, 2009 06:53
Show Gist options
  • Save jmhodges/180770 to your computer and use it in GitHub Desktop.
Save jmhodges/180770 to your computer and use it in GitHub Desktop.
require 'transformer'
require 'json'
some_canonical_example_of_input =
File.open('canonical.json'){|f| JSON.parse(f.read)}
another_canonical_example_of_input =
File.open('another.json'){|f| JSON.parse(f.read)}
MyHashTransformer = Transformer do
bed_matcher = m do |k,v|
k == "bed" && v =~ /^okay/
end
# Can't decide on the placement of the parentheses.
m "nice" => :just_okay
m "good", "okay" => :just_okay
m("good", "better", "best") => from_top(:good, :is_better)
m("good", "better", "sorta") => :oh_man
m("good", glob) => symbolize
m("yes", deep_glob) => symbolize
m("not_the_top", plus) => symbolize
bed_matcher => :fine
# Even if the value is nil, still do this thing.
nil_matcher("maybe", glob) => downcase.symbolize
m "complex" => proc do |k,v|
out[:complex] = do_complicated_stuff(v)
end
m "new_key_should_be_proc" => raw(proc {|s| does_a_thing(s) })
m "subhash" => MyOtherHashTransformer
# Speed up the matching by finding all the matches from the glob
# rules and turning them into explicit ones. The globs are then used
# after those match.
learn_possible_matchings_from(some_canonical_example_of_input)
learn_possible_matchings_from(another_canonical_example_of_input)
# Weighting might be nice?
# learn_likely_matchings_from(some_canonical_example_of_input)
# learn_likely_matchings_from(another_canonical_example_of_input)
# Everything not matching the layout of the canonical example hash
# is dropped completely. Those that match are turned into explicit rules.
# learn_only_matchings_from(some_canonical_example_of_input)
# learn_only_matchings_from(anonther_canonical_example_of_input)
end
p MyHashTransformer.class # => Class
p MyHashTransformer.tr("good" => {"hm" => "right"})
# => {:good => {:hm => "right"}
p MyHashTransformer.tr("good" => "right")
# => {:good => "right"}
p MyHashTransformer.tr("not_the_top" => {"hm" => "right"})
# => {"not_the_top" => {:hm => "right"}}
p MyHashTransformer.tr({"good" => {"okay" => 1}})
# => {:good => {:just_okay => 1}}
p MyHashTransformer.tr({"good" => {"better" => {"best" => 1}}})
# => {:good => {:is_better => 1}}
m("good", "better", "sorta") => :oh_man
p MyHashTransformer.tr({"good" => {"better" => {"sorta" => 2}}})
# => {:good => {:better => {:oh_man => 2}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment