Class: Boolean::Expression
- Inherits:
-
Object
- Object
- Boolean::Expression
show all
- Defined in:
- lib/boolean/expression.rb
Defined Under Namespace
Classes: Group, Logic, Name
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(base = Group.new) ⇒ Expression
Returns a new instance of Expression.
125
126
127
|
# File 'lib/boolean/expression.rb', line 125
def initialize (base = Group.new)
@base = base
end
|
Class Method Details
.parse(text) ⇒ Object
Also known as:
[]
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
# File 'lib/boolean/expression.rb', line 26
def parse (text)
base = Group.new
name = nil
stack = [base]
logic = nil
string = false
quoted = false
text.to_s.chars.each_with_index {|char, index|
begin
if !string && char == ')' && stack.length == 1
raise SyntaxError, 'closing an unopened parenthesis'
end
if !string && (char.match(/\s|\(|\)/) || (!logic && ['|', '&', '!'].member?(char)))
if logic || (name && name.match(/^(and|or|not)$/i) && !quoted)
stack.last << Logic.new(logic || name)
logic = nil
name = nil
elsif name
stack.last << Name.new(name)
name = nil
quoted = false
end
end
if name
if char == '"'
string = false
else
name << char
end
elsif logic
logic << char
else
if char == '"'
string = true
quoted = true
next
end
if string
name = char unless name
else
case char
when '(' then stack.push Group.new
when ')' then stack[-2] << stack.pop
when '|' then logic = '|'
when '&' then logic = '&'
when '!' then stack.last << Logic.new('!')
else name = char if !char.match(/\s/)
end
end
end
rescue SyntaxError => e
raise "#{e.message} near `#{text[index - 4, 8]}` at character #{index}"
end
}
raise SyntaxError, 'not all parenthesis are closed' if stack.length != 1
raise SyntaxError, 'the expression cannot end with a logic operator' if logic
base << Name.new(name) if name
base = base.first if base.length == 1 && base.first.is_a?(Group)
_check(base)
new(base)
end
|
Instance Method Details
#evaluate(*args) ⇒ Object
Also known as:
[]
129
130
131
132
133
|
# File 'lib/boolean/expression.rb', line 129
def evaluate (*args)
_evaluate(@base, args.flatten.compact.map {|piece|
piece.to_s
})
end
|
#names ⇒ Object
137
138
139
|
# File 'lib/boolean/expression.rb', line 137
def names
_names(@base).compact.uniq
end
|
#to_a ⇒ Object
149
150
151
|
# File 'lib/boolean/expression.rb', line 149
def to_a
@base.to_a
end
|
#to_group ⇒ Object
145
146
147
|
# File 'lib/boolean/expression.rb', line 145
def to_group
@base
end
|
#to_s ⇒ Object
141
142
143
|
# File 'lib/boolean/expression.rb', line 141
def to_s
@base.inspect
end
|