Class: ExecJS::JohnsonRuntime::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/execjs/johnson_runtime.rb

Instance Method Summary collapse

Constructor Details

#initialize(source = "") ⇒ Context

Returns a new instance of Context.



4
5
6
7
# File 'lib/execjs/johnson_runtime.rb', line 4

def initialize(source = "")
  @runtime = Johnson::Runtime.new
  @runtime.evaluate(source)
end

Instance Method Details

#call(properties, *args) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/execjs/johnson_runtime.rb', line 31

def call(properties, *args)
  unbox @runtime.evaluate(properties).call(*args)
rescue Johnson::Error => e
  if syntax_error?(e)
    raise RuntimeError, e.message
  else
    raise ProgramError, e.message
  end
end

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



17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/execjs/johnson_runtime.rb', line 17

def eval(source, options = {})
  source = source.encode('UTF-8') if source.respond_to?(:encode)

  if /\S/ =~ source
    unbox @runtime.evaluate("(#{source})")
  end
rescue Johnson::Error => e
  if syntax_error?(e)
    raise RuntimeError, e.message
  else
    raise ProgramError, e.message
  end
end

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



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

def exec(source, options = {})
  source = source.encode('UTF-8') if source.respond_to?(:encode)

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

#unbox(value) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/execjs/johnson_runtime.rb', line 41

def unbox(value)
  case
  when function?(value)
    nil
  when string?(value)
    value.respond_to?(:force_encoding) ?
      value.force_encoding('UTF-8') :
      value
  when array?(value)
    value.map { |v| unbox(v) }
  when object?(value)
    value.inject({}) do |vs, (k, v)|
      vs[k] = unbox(v) unless function?(v)
      vs
    end
  else
    value
  end
end