Class: WLang::Scope

Inherits:
Object
  • Object
show all
Defined in:
lib/wlang/scope.rb,
lib/wlang/scope/null_scope.rb,
lib/wlang/scope/proc_scope.rb,
lib/wlang/scope/object_scope.rb,
lib/wlang/scope/binding_scope.rb,
lib/wlang/scope/sinatra_scope.rb

Direct Known Subclasses

BindingScope, NullScope, ObjectScope, ProcScope

Defined Under Namespace

Classes: BindingScope, NullScope, ObjectScope, ProcScope, SinatraScope

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subject) ⇒ Scope

Returns a new instance of Scope.



7
8
9
10
# File 'lib/wlang/scope.rb', line 7

def initialize(subject)
  @subject = subject
  @parent  = nil
end

Instance Attribute Details

#parentObject (readonly)

Returns the value of attribute parent.



5
6
7
# File 'lib/wlang/scope.rb', line 5

def parent
  @parent
end

#subjectObject (readonly)

Returns the value of attribute subject.



4
5
6
# File 'lib/wlang/scope.rb', line 4

def subject
  @subject
end

Class Method Details

.chain(scopes) ⇒ Object



28
29
30
# File 'lib/wlang/scope.rb', line 28

def self.chain(scopes)
  scopes.compact.inject(Scope.null){|p,c| p.push(c)}
end

.coerce(arg) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/wlang/scope.rb', line 16

def self.coerce(arg)
  case arg
    when Hash       then ObjectScope.new(arg)
    when Scope      then arg
    when SinatraApp then SinatraScope.new(arg)
    when Binding    then BindingScope.new(arg)
    when Proc       then ProcScope.new(arg)
    else
      ObjectScope.new(arg)
  end
end

.nullObject



12
13
14
# File 'lib/wlang/scope.rb', line 12

def self.null
  @null ||= NullScope.new
end

Instance Method Details

#evaluate(expr, dialect, *default, &bl) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/wlang/scope.rb', line 48

def evaluate(expr, dialect, *default, &bl)
  expr = expr.to_s.strip
  unfound = lambda do
    if default.empty?
      bl ? bl.call(expr) : throw(:fail)
    else
      default.first
    end
  end
  if expr.index('.').nil?
    fetch(expr.to_sym, dialect, unfound)
  else
    keys = expr.split('.').map(&:to_sym)
    keys.inject(self){|scope,key|
      found = scope.fetch(key, dialect, unfound)
      Scope.coerce(found)
    }.subject
  end
end

#popObject



40
41
42
# File 'lib/wlang/scope.rb', line 40

def pop
  @parent
end

#push(x) ⇒ Object



36
37
38
# File 'lib/wlang/scope.rb', line 36

def push(x)
  append(Scope.coerce(x))
end

#rootObject



32
33
34
# File 'lib/wlang/scope.rb', line 32

def root
  parent ? parent.root : self
end

#subjectsObject



68
69
70
71
72
# File 'lib/wlang/scope.rb', line 68

def subjects
  arr = []
  visit(:top_down){|s| arr << s.subject}
  arr
end

#with(x) {|self.push(x)| ... } ⇒ Object

Yields:



44
45
46
# File 'lib/wlang/scope.rb', line 44

def with(x)
  yield(self.push(x))
end