module MovieMasher::Evaluate
evaluates certain simple expressions
Attributes
__calculator[RW]
Public Class Methods
calculator()
click to toggle source
# File lib/util/evaluate.rb, line 11 def calculator Evaluate.__calculator ||= Dentaku::Calculator.new end
coerce_if_numeric(value)
click to toggle source
# File lib/util/evaluate.rb, line 15 def coerce_if_numeric(value) v_str = value.to_s unless v_str.include?(' ') sym = (v_str.include?('.') ? :to_f : :to_i) value = value.send(sym) if v_str == v_str.send(sym).to_s end value end
equation(string, raise_on_fail = nil)
click to toggle source
# File lib/util/evaluate.rb, line 24 def equation(string, raise_on_fail = nil) evaluated = string # change all numbers to floats fs = string.to_s.gsub(/([0-9]+[.]?[0-9]*)/, &:to_f) fs = "0 + (#{fs})" begin # puts "Evaluating: #{fs} #{fs.class.name}" evaluated = calculator.evaluate!(fs) evaluated = evaluated.to_f if evaluated.is_a?(BigDecimal) # puts "Evaluated: #{evaluated} #{evaluated.class.name}" rescue StandardError => e if raise_on_fail raise(Error::JobInput, "evaluation failed #{fs} #{e.message}") end end evaluated end
object(data, scope = nil)
click to toggle source
# File lib/util/evaluate.rb, line 42 def object(data, scope = nil) scope ||= {} keys = (data.is_a?(Array) ? (0..(data.length - 1)) : data.keys) keys.each do |k| v = data[k] if __is_eval_object?(v) object(v, scope) # recurse elsif v.is_a?(Proc) data[k] = v.call else data[k] = value(v.to_s, scope) end end end
value(string, scope = nil)
click to toggle source
# File lib/util/evaluate.rb, line 57 def value(string, scope = nil) scope ||= {} split_value = __split(string) unless split_value.empty? # otherwise there are no curly braces string = '' is_static = true split_value.each do |bit| if is_static string += bit else split_bit = bit.split '.' child = __scope_target(split_bit, scope) # shifts off first evaled = nil evaled = __evaluated_scope_child(child, split_bit) if child string = if __is_eval_object?(evaled) evaled elsif evaled.is_a?(Proc) evaled.call else "#{string}#{evaled}" end end is_static = !is_static end end string end