From: Knut Franke Date: 2010-09-13T06:10:23+09:00 Subject: Declarative relations between object attributes Some time ago I stumbled over Cells[1], a Common Lisp extension allowing one to declare relations between instance variables (called slots in CL); i.e. a change to one variable will automatically recompute other variables depending on it. I think it's pretty neat, but using it in any interesting context is somewhat hampered by the fact that few people go through the considerable trouble involved in learning Common Lisp. Just today it occurred to me that it should be pretty easy to do something similar in Ruby. Indeed, a couple of codelines later, I had a Ruby version of the standard Cells example (well, a simplified version) running: class Motor cell :temperature, :status def initialize self.temperature = 0 calculate :status do if self.temperature < 100 :on else :off end end end end m = Motor.new m.observe(:temperature) { |old, new| puts "temperature: #{old} -> #{new}" } m.observe(:status) { |old, new| puts "status: #{old} -> #{new}" } m.temperature = 80 m.temperature = 110 => temperature: 0 -> 80 temperature: 80 -> 110 status: on -> off That's certainly not dramatically new; you can do similar things with the observer pattern or Qt signals, for example. However, I like the idea of just declaring that one variable (status) is a certain function of one or more other variables (temperature) and have the library take care of all the rest. Makes for cleaner code, particularly if you do model/view programming (see model-view.rb in [2]). I'm not yet sure what to do with this. Possibly similar/better solutions already exist. Certainly the code needs some work. So I figured that before going further I'd try to get some feedback; particularly * Do you think this is useful? * Do you know related projects? * What could be improved? I've put the code on github[1]. Any input appreciated. Thanks. Knut [1] http://common-lisp.net/project/cells/ [2] http://github.com/nome/ruby-cells -- Posted via http://www.ruby-forum.com/.