Is there a way to provide similar functionality in ruby to what add-watch does in clojure? I am looking for a way to register a block/proc/lambda as a callback on a data structure, say a hash, and be called whenever the state of the hash changes.
Share
Yes, you can do this in Ruby, but you’ll need to build up the infrastructure yourself or find a library that does it.
Because of Ruby’s “duck” typing, a method that expects a Hash instance can be given a class instance that looks, feels, and sounds like a hash. The receiving method can just treat the object as a hash and everything will be fine.
Meanwhile, your other software will know that it is really an
ObservableHash(or whatever you decide to call it.) And you will have registered your callback-on-change methods, etc.Here’s a blog post that will help get you started on creating your
ObservableHash.A final tip: be sure to implement all of the Hash methods. That way the other methods that receive it won’t be able to tell the difference between an observable_hash and a hash.
It is my understanding that the Rails
ActionController#params“hash” is, in fact, a class instance that seems to be a hash (but really isn’t). Look up its source to check it out.