Module: Js2json

Defined in:
lib/js2json.rb,
lib/js2json/version.rb,
lib/js2json/ruby_scope.rb,
lib/js2json/v8_converter.rb

Defined Under Namespace

Classes: RubyScope, V8Converter

Constant Summary collapse

VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.js2json(expr, options = {}) ⇒ Object



31
32
33
34
# File 'lib/js2json.rb', line 31

def js2json(expr, options = {})
  rb_obj = js2ruby(expr, options)
  JSON.pretty_generate(rb_obj)
end

.js2ruby(expr, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/js2json.rb', line 9

def js2ruby(expr, options = {})
  unless expr.kind_of?(String)
    raise TypeError, "wrong argument type #{expr.class} (expected String)"
  end

  unless options.kind_of?(Hash)
    raise TypeError, "wrong argument type #{options.class} (expected Hash)"
  end

  cxt = V8::Context.new
  cxt['Ruby']  = Js2json::RubyScope.new
  cxt['load']  = cxt.method(:load)
  cxt['print'] = Kernel.method(:puts)

  expr = "(#{expr})" if options[:bracket_script]
  obj = cxt.eval(expr)

  converter = Js2json::V8Converter.new(options)
  converter.convert_to_ruby(obj)
end