lib/ruote/exp/condition.rb in ruote-2.2.0 vs lib/ruote/exp/condition.rb in ruote-2.3.0

- old
+ new

@@ -1,7 +1,7 @@ #-- -# Copyright (c) 2005-2011, John Mettraux, jmettraux@gmail.com +# Copyright (c) 2005-2012, John Mettraux, jmettraux@gmail.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell @@ -50,12 +50,12 @@ 'evl_in' => /^(.+?)( +is)?( +not)?( +in +)(\[.*\]|\{.*\})$/ } def self.apply?(sif, sunless) - return (true?(sif)) if sif - return ( ! true?(sunless)) if sunless + return (true?(sif)) if sif != nil + return ( ! true?(sunless)) if sunless != nil true end # Returns true if the given conditional string evaluates to true. @@ -63,22 +63,28 @@ def self.true?(conditional) conditional = unescape(conditional.to_s) REGEXES.each do |method, regex| - if m = regex.match(conditional) - return self.send(method, m) - end + m = regex.match(conditional) + return self.send(method, m) if m end evl(conditional) ? true : false rescue ArgumentError => ae raise ConditionError.new(conditional) end + # Returns true if the given conditional string evaluates to false. + # + def self.false?(conditional) + + ( ! true?(conditional)) + end + # Evaluates the given [conditional] code string and returns the # result. # # Note : this is not a full Ruby evaluation ! # @@ -93,17 +99,15 @@ protected def self.parse(conditional) - Rufus::TreeChecker.parse(conditional) + Ruote.parse_ruby(conditional) - rescue NoMethodError => nme + rescue SyntaxError => se - raise NoMethodError.new( - "/!\\ please upgrade your rufus-treechecker gem /!\\" - ) + [ :str, conditional ] rescue => e [ :false ] end @@ -145,20 +149,41 @@ if tree[0] == :call && COMPARATORS.include?(tree[2]) return evl(tree[1]).send(tree[2], evl(tree.last.last)) end - return flatten(tree) if tree[0] == :call + if (c = flatten_and_compare(tree)) != nil + return c + end + if tree[0] == :call + return flatten(tree) + end + raise ArgumentError + # TODO : consider returning false #require 'ruby2ruby' #Ruby2Ruby.new.process(Sexp.from_array(tree)) # returns the raw Ruby as a String # it's nice but "Loan/Grant" becomes "(Loan / Grant)" end - KEYWORDS = %w[ call const arglist ].collect { |w| w.to_sym } + def self.flatten_and_compare(tree) + + ftree = tree.flatten + comparator = (ftree & COMPARATORS).first + + return nil unless comparator + + icomparator = ftree.index(comparator) + left = ftree[0..icomparator - 1] + right = ftree[icomparator + 1..-1] + + evl("#{flatten(left).inspect} #{comparator} #{flatten(right).inspect}") + end + + KEYWORDS = %w[ call const arglist str ].collect { |w| w.to_sym } def self.flatten(tree) (tree.flatten - KEYWORDS).collect { |e| e.nil? ? ' ' : e.to_s }.join.strip end