Class: JavaScript::Scope

Inherits:
BlankObject show all
Includes:
Internals, Syntax
Defined in:
lib/javascript.rb

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil, target = nil, locals = {}) ⇒ Scope

Returns a new instance of Scope.



164
165
166
167
168
169
170
171
172
173
174
# File 'lib/javascript.rb', line 164

def initialize(parent = nil, target = nil, locals = {})
  @parent = parent
  @global = parent ? parent.__global__ : GlobalObject.new
  @locals = locals

  if Scope === target
    @target = target.__target__
  else
    @target = target || global
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object (private)



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/javascript.rb', line 208

def method_missing(name, *args, &block)
  found   = false
  value   = nil
  defined = __caller__.local_variable_defined?(name) rescue nil

  if defined
    found = true
    value = __caller__.local_variable_get(name)
  elsif @locals.key?(name)
    found = true
    value = @locals[name]
  elsif !@parent && @global.__defined__?(name)
    found = true
    value = @global[name]
  end

  if found && Function === value
    value.apply(nil, args)
  elsif found
    value
  elsif @parent
    @parent.__send__(name, *args, &block)
  elsif block.nil?
    Identifier.new(name, args)
  else
    Function.new(name, args, block)
  end
end

Instance Method Details

#__eval__(*args, &block) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/javascript.rb', line 188

def __eval__(*args, &block)
  JavaScript.current_scope = self

  # convert the block to a lambda, so that +return+ works correctly
  temp      = :"block_#{Time.now.to_i}"
  metaclass = __method__(:singleton_class).call

  metaclass.send(:define_method, temp, &block)

  if block.arity.zero?
    __method__(:send).call(temp)
  else
    __method__(:send).call(temp, *args)
  end
ensure
  JavaScript.current_scope = @parent
  metaclass.send(:remove_method, temp)
end

#__global__Object



176
177
178
# File 'lib/javascript.rb', line 176

def __global__
  @global
end

#__spawn__(target = nil, locals = {}) ⇒ Object



184
185
186
# File 'lib/javascript.rb', line 184

def __spawn__(target = nil, locals = {})
  Scope.new(self, target, locals)
end

#__target__Object



180
181
182
# File 'lib/javascript.rb', line 180

def __target__
  @target
end