Class: ExpressionProcessor::Expression
- Inherits:
-
Object
- Object
- ExpressionProcessor::Expression
- Defined in:
- lib/expression_processor.rb
Instance Attribute Summary collapse
-
#constants ⇒ Object
Returns the value of attribute constants.
-
#errors ⇒ Object
Returns the value of attribute errors.
-
#expression ⇒ Object
Returns the value of attribute expression.
Instance Method Summary collapse
- #eval ⇒ Object
-
#initialize(expression) ⇒ Expression
constructor
A new instance of Expression.
- #preprocess ⇒ Object
- #tokenize ⇒ Object
- #valid?(constants = nil) ⇒ Boolean
Constructor Details
#initialize(expression) ⇒ Expression
Returns a new instance of Expression.
11 12 13 14 15 |
# File 'lib/expression_processor.rb', line 11 def initialize(expression) @constants = {} @errors = [] @expression = expression || "" end |
Instance Attribute Details
#constants ⇒ Object
Returns the value of attribute constants.
9 10 11 |
# File 'lib/expression_processor.rb', line 9 def constants @constants end |
#errors ⇒ Object
Returns the value of attribute errors.
9 10 11 |
# File 'lib/expression_processor.rb', line 9 def errors @errors end |
#expression ⇒ Object
Returns the value of attribute expression.
9 10 11 |
# File 'lib/expression_processor.rb', line 9 def expression @expression end |
Instance Method Details
#eval ⇒ Object
21 22 23 24 25 26 |
# File 'lib/expression_processor.rb', line 21 def eval proxy = Proxy.new(@constants) untainted = preprocess.untaint result = valid? ? proc { $SAFE = 3; proxy.instance_eval(untainted) }.call : 0 result.to_f.round(2) end |
#preprocess ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/expression_processor.rb', line 28 def preprocess executable = @expression.downcase tokenize.each do |token| case token[0] # ignore dollar signs when :dollar executable.gsub!(/\$/, '') # convert percent to decimal 10% => 0.10 when :percent executable.gsub!(/(#{token[1]})/) {|match| match.gsub(/(%)/, '').to_f / 100 } end end # HACK: make sure operators have surrounding whitespace or calculations dont always # have correct result (possibly an eval issue?) executable.gsub!(/([%\/*+-])/, " \\1 ") executable end |
#tokenize ⇒ Object
47 48 49 |
# File 'lib/expression_processor.rb', line 47 def tokenize @tokens ||= Lexer.new(@expression).tokenize end |
#valid?(constants = nil) ⇒ Boolean
51 52 53 54 |
# File 'lib/expression_processor.rb', line 51 def valid?(constants = nil) validate(constants) @errors.empty? end |