Permalink
Browse files

A Monitor can be dlaced with a name and some event listeners, and

subclasses also have the same name/listeners
  • Loading branch information...
1 parent cacc39a commit 63e4db8db7cdaec5bfa5b2b668a9057896481d0f @telent committed Apr 21, 2012
Showing with 75 additions and 1 deletion.
  1. +4 −0 lib/lizard.rb
  2. +30 −0 lib/lizard/monitor.rb
  3. +1 −1 lib/lizard/version.rb
  4. +40 −0 test/unit/monitor_test.rb
View
4 lib/lizard.rb
@@ -0,0 +1,4 @@
+require 'lizard/version'
+class Lizard; end
+require 'lizard/monitor'
+
View
30 lib/lizard/monitor.rb
@@ -0,0 +1,30 @@
+require 'pp'
+class Lizard; end
+
+class Lizard::Monitor
+ class << self
+ def name(value)
+ define_method :name do
+ value
+ end
+ end
+ def listen(event,&blk)
+ @clisteners||=Hash.new {|h,k| h[k]=[] }
+ @clisteners[event] << blk
+ end
+ end
+
+ attr_reader :listeners
+ def init_listeners(clss=self.class)
+ @listeners ||= {}
+ @listeners=@listeners.merge(clss.instance_variable_get(:@clisteners) ||{})
+ if (sup=clss.superclass) != Object
+ init_listeners sup
+ end
+ end
+
+ def initialize
+ init_listeners
+ end
+
+end
View
2 lib/lizard/version.rb
@@ -1,4 +1,4 @@
# encoding: utf-8
-module Lizard
+class Lizard
VERSION = "0.0".freeze
end
View
40 test/unit/monitor_test.rb
@@ -0,0 +1,40 @@
+require 'lizard/monitor'
+
+describe Lizard::Monitor do
+ it "a subclass retains the setup done in its parent" do
+ m=Class.new(Lizard::Monitor) do
+ name "anguimorph"
+ end
+ m2=Class.new(m)
+ assert_equal "anguimorph",m.new.name
+ assert_equal "anguimorph",m2.new.name
+ end
+
+ describe "events" do
+ it "#listen registers an event handler" do
+ succeeded=nil
+ m=Class.new(Lizard::Monitor) do
+ listen :enable do
+ succeeded=true
+ end
+ end.new
+ assert_equal 1, m.listeners[:enable].length
+ m.listeners[:enable].map(&:call)
+ assert succeeded
+ end
+ it "handlers are inherited" do
+ succeeded=nil
+ m=Class.new(Lizard::Monitor) do
+ listen :enable do
+ succeeded=true
+ end
+ end
+ m2=Class.new(m).new
+ assert_equal 1, m2.listeners[:enable].length
+ m2.listeners[:enable].map(&:call)
+ assert succeeded
+ end
+ end
+end
+
+

0 comments on commit 63e4db8

Please sign in to comment.