Module: GoodGuide::Gibbon::Util

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

Instance Method Summary collapse

Instance Method Details

#hash_to_ruby(js_hash) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/goodguide/gibbon.rb', line 9

def hash_to_ruby(js_hash)
  return nil unless js_hash

  ruby_hash = { '__isHash__' => true }

  js_hash[:each].methodcall(js_hash, lambda { |this, k, v|
    ruby_hash[k] = obj_to_ruby(v)
  })

  ruby_hash
end

#obj_to_js(o) ⇒ Object



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

def obj_to_js(o)
  case o
  when Array
    o.map { |x| obj_to_js(x) }
  when Hash
    if o['__isHash__'] or 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['_union'] or o[:_union]
      union = o['_union'] or o[:_union]
      tag = o['_tag'] or o[:_tag]
      constructor = gibbon[union]
      raise "unknown union #{union}" unless constructor && constructor.tags
      names = constructor.tags[tag]
      raise "unknown tag #{tag}" unless names.is_a? V8::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



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/goodguide/gibbon.rb', line 54

def obj_to_ruby(o)
  case o
  when V8::Array
    o.map { |x| obj_to_ruby(x) }
  when V8::Object
    if o[:__isHash__]
      hash_to_ruby(o)
    else
      o = o.asJSON if o.respond_to? :asJSON

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