Module: GoodGuide::Gibbon::Util

Extended by:
Util
Included in:
Context, RuntimeClient, SemanticError, StaticClient, Util
Defined in:
lib/goodguide/gibbon.rb

Instance Method Summary collapse

Instance Method Details

#hash_to_ruby(js_hash) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/goodguide/gibbon.rb', line 23

def hash_to_ruby(js_hash)
  return nil unless js_hash

  ruby_hash = { '__isHash__' => true }

  js_hash[:each].methodcall(js_hash, lambda { |a, b, c|
    k, v = defined?(JRUBY_VERSION) ? [a, b] : [b, c]
    ruby_hash[k] = obj_to_ruby(v)
  })

  ruby_hash
end

#obj_to_js(o) ⇒ Object



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
# File 'lib/goodguide/gibbon.rb', line 36

def obj_to_js(o)
  case o
  when Array
    o.map { |x| obj_to_js(x) }
  when Hash
    if o['__isHash__']
      js_hash = gibbon[:Hash].new
      o.each do |k, v|
        next if k.to_s == '__isHash__'
        js_hash.set(k, obj_to_js(v))
      end
      js_hash
    elsif o['__isVariant__']
      type = o['_type']
      tag = o['_tag']
      constructor = gibbon[type]
      raise "unknown union #{type}" unless constructor && constructor.tags
      names = constructor.tags[tag]
      raise "unknown tag #{tag}" unless names.is_a?(JSArray) or names.is_a?(Array)

      vals = names.map do |name|
        obj_to_js(o[name])
      end

      constructor[tag].methodcall(constructor, *vals)
    else
      o
    end
  else
    o
  end
end

#obj_to_ruby(o) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/goodguide/gibbon.rb', line 69

def obj_to_ruby(o)
  case o
  when JSArray, Array
    o.map { |x| obj_to_ruby(x) }
  when JSString
    o.to_s
  when JSObject
    if o[:__isHash__]
      hash_to_ruby(o)
    elsif o[:__isVariant__]
      out = {
        '__isVariant__' => true,
        '_names' => obj_to_ruby(o[:_names]),
        '_type' => o[:_type],
        '_tag' => o[:_tag]
      }

      o._names.each do |name|
        out[name] = obj_to_ruby o[name]
      end

      out
    else
      out = {}
      o.each do |k, v|
        out[k] = obj_to_ruby(v)
      end
      out
    end
  else
    o
  end
end