jmhodges (owner)

Revisions

gist: 180770 Download_button fork
public
Public Clone URL: git://gist.github.com/180770.git
Embed All Files: show embed
transformer_example.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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}}}