Class: ExecJS::RubyRhinoRuntime::Context

Inherits:
ExecJS::Runtime::Context show all
Defined in:
lib/execjs/ruby_rhino_runtime.rb

Instance Method Summary collapse

Constructor Details

#initialize(runtime, source = "", options = {}) ⇒ Context

Returns a new instance of Context.



7
8
9
10
11
12
13
14
15
# File 'lib/execjs/ruby_rhino_runtime.rb', line 7

def initialize(runtime, source = "", options = {})
  source = source.encode(Encoding::UTF_8)

  @rhino_context = ::Rhino::Context.new
  fix_memory_limit! @rhino_context
  @rhino_context.eval(source)
rescue Exception => e
  raise wrap_error(e)
end

Instance Method Details

#call(properties, *args) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/execjs/ruby_rhino_runtime.rb', line 35

def call(properties, *args)
  # Might no longer be necessary if therubyrhino handles Symbols directly:
  # https://github.com/rubyjs/therubyrhino/issues/43
  converted_args = JSON.parse(JSON.generate(args), create_additions: false)

  unbox @rhino_context.eval(properties).call(*converted_args)
rescue Exception => e
  raise wrap_error(e)
end

#eval(source, options = {}) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/execjs/ruby_rhino_runtime.rb', line 25

def eval(source, options = {})
  source = source.encode(Encoding::UTF_8)

  if /\S/ =~ source
    unbox @rhino_context.eval("(#{source})")
  end
rescue Exception => e
  raise wrap_error(e)
end

#exec(source, options = {}) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/execjs/ruby_rhino_runtime.rb', line 17

def exec(source, options = {})
  source = source.encode(Encoding::UTF_8)

  if /\S/ =~ source
    eval "(function(){#{source}})()", options
  end
end

#unbox(value) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/execjs/ruby_rhino_runtime.rb', line 45

def unbox(value)
  case value = ::Rhino::to_ruby(value)
  when Java::OrgMozillaJavascript::NativeFunction
    nil
  when Java::OrgMozillaJavascript::NativeObject
    value.inject({}) do |vs, (k, v)|
      case v
      when Java::OrgMozillaJavascript::NativeFunction, ::Rhino::JS::Function
        nil
      else
        vs[k] = unbox(v)
      end
      vs
    end
  when Array
    value.map { |v| unbox(v) }
  else
    value
  end
end

#wrap_error(e) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/execjs/ruby_rhino_runtime.rb', line 66

def wrap_error(e)
  return e unless e.is_a?(::Rhino::JSError)

  error_class = e.message == "syntax error" ? RuntimeError : ProgramError

  stack = e.backtrace
  stack = stack.map { |line| line.sub(" at ", "").sub("<eval>", "(execjs)").strip }
  stack.unshift("(execjs):1") if e.javascript_backtrace.empty?

  error = error_class.new(e.value.to_s)
  error.set_backtrace(stack)
  error
end