class Ruby2JS::Namespace

Public Class Methods

new() click to toggle source
# File lib/ruby2js/namespace.rb, line 16
def initialize
  @active = [] # current scope
  @seen = {}   # history of all definitions seen previously
end

Public Instance Methods

active() click to toggle source

return the active scope as a flat array of symbols

# File lib/ruby2js/namespace.rb, line 31
def active
  @active.flatten.compact
end
defineProps(props, namespace=active) click to toggle source

add new props (and methods) to the current scope.

# File lib/ruby2js/namespace.rb, line 52
def defineProps(props, namespace=active)
  @seen[namespace] ||= {}
  @seen[namespace].merge! props || {}
end
enter(name) click to toggle source

enter a new scope, which may be a nested subscope. Mark the new scope as seen, and return any previous definition that may have been seen before.

# File lib/ruby2js/namespace.rb, line 38
def enter(name)
  @active.push resolve(name)
  previous = @seen[active]
  @seen[active] ||= {}
  previous
end
find(name) click to toggle source

find a named scope which may be relative to any point in the ancestry of the current scope. Return the properties for that scope.

# File lib/ruby2js/namespace.rb, line 59
def find(name)
  name = resolve(name)
  prefix = active
  while prefix.pop
    result = @seen[prefix + name]
    return result if result
  end
  {}
end
getOwnProps(name = nil) click to toggle source

return the set of known properties (and methods) for either the current scope or a named subscope.

# File lib/ruby2js/namespace.rb, line 47
def getOwnProps(name = nil)
  @seen[active + resolve(name)]&.dup || {}
end
leave() click to toggle source

leave a given scope. Note that the scope may be compound (e.g., M::N), and if so, it will pop the entire resolved name.

# File lib/ruby2js/namespace.rb, line 71
def leave()
  @active.pop
end
resolve(token, result = []) click to toggle source

convert an AST name which is represented as a set of nested s(:const, # …) into an array of symbols that represent the relative path.

# File lib/ruby2js/namespace.rb, line 24
def resolve(token, result = [])
  return [] unless token&.type == :const
  resolve(token.children.first, result)
  result.push(token.children.last)
end