Sha256: 89f343184fa93b81cb3dcb0e5609895f66cbe19e9b4e64bb3f5aea74d405140d

Contents?: true

Size: 931 Bytes

Versions: 25

Compression:

Stored size: 931 Bytes

Contents

# From: http://www.infoq.com/articles/properties-metaprogramming

module Properties  
  def self.extended(base) 
    base.class_eval %{
      def fire_event_for(sym, arg) 
        return if !@listener[sym]
        @listener[sym].each {|l| l.call(arg) } 
      end 
    }
  end
  
  # def property(sym, &predicate)
  def property(sym, predicate=nil)
    define_method(sym) do
      instance_variable_get("@#{sym}")
    end
  
    define_method("#{sym}=") do |arg|
      return if !predicate.call(arg) if predicate
      instance_variable_set("@#{sym}", arg)
      fire_event_for(sym, arg)
    end
  
    define_method("add_#{sym}_listener") do |x| 
      @listener ||= {}
      @listener[sym] ||= []
      @listener[sym] << x
    end
    
    define_method("remove_#{sym}_listener") do |x| 
      return if !@listener[sym]
      @listener[sym].delete_at(x)
    end
  end
  
  def is(test)
    lambda {|val| test === val }
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
sugar-high-0.4.6 lib/sugar-high/properties.rb
sugar-high-0.4.5.2 lib/sugar-high/properties.rb
sugar-high-0.4.5 lib/sugar-high/properties.rb
sugar-high-0.4.4.2 lib/sugar-high/properties.rb
sugar-high-0.4.4.1 lib/sugar-high/properties.rb