Sha256: 519a1f20e7eae685f3172e1027feb1cb5a78d5c8aca3334dd7f6ddbb1eb948de

Contents?: true

Size: 911 Bytes

Versions: 4

Compression:

Stored size: 911 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

4 entries across 4 versions & 1 rubygems

Version Path
sugar-high-0.7.3 lib/sugar-high/properties.rb
sugar-high-0.7.2 lib/sugar-high/properties.rb
sugar-high-0.7.1 lib/sugar-high/properties.rb
sugar-high-0.7.0 lib/sugar-high/properties.rb