Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Mickael

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Property change listener

How to implement a Property change listener on ruby class
Origin : http://rawblock.blogspot.com/2007/02/transparent-property-change-listeners.html

class ListenerSupport
 
  def self.listen_to(klass, *properties)
    setup(klass)
    properties.each do |p|
      klass.instance_eval do
        #rename original method
        alias_method "#{p}_orig=", "#{p}="
        #create proxy method in it's place that will fire
        #changes, and delegate to the original implementation
        define_method "#{p}=" do |value|
          old_value = send "#{p}"
          send "#{p}_orig=",value
          fire_property_changed p, old_value, value
        end
      end
    end
  end
 
  def self.setup(klass)
    klass.instance_eval do
     
      define_method :fire_property_changed do |prop, pre, post|
        return if pre == post
        eval %{
          @listeners[prop].each do |l|
              l.property_changed(self, prop, pre, post)
          end unless @listeners.nil?
        }
      end unless instance_methods.include? :fire_property_changed
     
      define_method :add_property_listener do |prop, listener|
        eval %{
          @listeners = {} if @listeners.nil?
          prop_listeners = @listeners.include?(prop) ? @listeners[prop] : []
          @listeners[prop] = prop_listeners
          prop_listeners << listener unless prop_listeners.include? listener
        }
      end unless instance_methods.include? :add_property_listener
     
    end
  end
 
end


The general idea is that the original class is modified so that all properties that are listened to have their accessor write methods intercepted, and any property change listeners are notified when that property changes.

Let's walk through how it works:

* A standard Ruby class with property accessors is created. e.g.

class RubyBean
attr_accessor :foo, :bar
end

* A call to ListenerSupport.listen_to is made to modify the class to allow properties to be listened to.

ListenerSupport.listen_to RubyBean, :foo, :bar

* listen_to adds methods add_property_listener and fire_property_changed to allow listeners to be added to RubyBean for specific properties.
* listen_to then aliases the original methods foo= and bar= to foo_orig= and bar_orig=. New methods for foo= and bar= are defined that delegate the work to the original method, then call fire_property_changed to notify the listeners.
* Listeners are called, and any custom action (such as GUI component binding) can be carried out.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS