Class: ExpressionProcessor::Expression

Inherits:
Object
  • Object
show all
Defined in:
lib/expression_processor.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#constantsObject

Returns the value of attribute constants.



9
10
11
# File 'lib/expression_processor.rb', line 9

def constants
  @constants
end

#errorsObject

Returns the value of attribute errors.



9
10
11
# File 'lib/expression_processor.rb', line 9

def errors
  @errors
end

#expressionObject

Returns the value of attribute expression.



9
10
11
# File 'lib/expression_processor.rb', line 9

def expression
  @expression
end

Instance Method Details

#evalObject



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

#preprocessObject



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

#tokenizeObject



47
48
49
# File 'lib/expression_processor.rb', line 47

def tokenize
  @tokens ||= Lexer.new(@expression).tokenize
end

#valid?(constants = nil) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
54
# File 'lib/expression_processor.rb', line 51

def valid?(constants = nil)
  validate(constants)
  @errors.empty?
end