On Wed, 26 May 2004, Florian Weber wrote: > hi! > > im trying to define a set of rules with ruby, however i cant find a more > ruby-like way to do so.. > > instead of doing something like > > my_set.add(NotNamedRule("orange").new) > my_set.add(HasPropertyRule("color").new) > my_set.add(OrRule(HasPropertyRule("size").new, > HasPropertyRule("weight").new)) > > (i know this is a horrible example. excuse the awful 'design'. its > justs to illustrate > what i not wanna have ; ) > > i wanna do something like > > my_set.rules = !name("orange") && hasProperty("color") && > (hasProperty("size") || hasProperty("weight")) > > can anybody think of a nice way to do this? > > thanks a lot for any feedback! > > ciao! > florian if you like dangerous code, you might try something __like__ this: ~ > cat a.rb class Rule def initialize rule; @rule = rule.to_str; end def apply? obj safe = $SAFE thread = nil begin thread = Thread.new(obj) do |obj| $SAFE = 12 obj.instance_eval @rule end thread.join ensure $SAFE = safe end thread.value end class << self; alias [] new; end module Obeyer def obey?(*rules) rules.flatten.select{|rule| not rule.apply?(self)}.empty? ? true : false end end end class Agent include Rule::Obeyer attr :color attr :size def initialize opts = {} @color, @size = opts.values_at 'color', 'size' end end agent = Agent.new 'color'=>'red', 'size'=>42 rules = Rule[ 'color == "red" or color == "blue"' ], Rule[ 'size == 42' ] p(agent.obey?(rules)) # => true rules = Rule[ 'color == "purple"' ], Rule[ 'size == 42' ] p(agent.obey?(rules)) # => false ~ > ruby a.rb true false -a -- =============================================================================== | EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov | PHONE :: 303.497.6469 | ADDRESS :: E/GC2 325 Broadway, Boulder, CO 80305-3328 | URL :: http://www.ngdc.noaa.gov/stp/ | "640K ought to be enough for anybody." - Bill Gates, 1981 ===============================================================================