Permalink
Browse files

Support different data structures for eyes.

You may no specify the type of data structure you want to use in the
constructor, causing a class of a corresponding name to be the object that
handles .see and .seen?. Currently, Array and Hash are supported.
  • Loading branch information...
1 parent 56d7261 commit e73827d4b5f2e33ba1a996d3262aa5c2c80bfab4 @runpaint committed Apr 27, 2009
Showing with 55 additions and 21 deletions.
  1. +35 −11 lib/eye.rb
  2. +14 −8 spec/eye/seen_spec.rb
  3. +6 −2 spec/eye/type_spec.rb
View
@@ -1,21 +1,45 @@
class Eye
DEFAULT_TYPE = :hash
- attr_reader :type, :eye
+ attr_reader :type
def initialize(args={})
unless args.empty?
- raise ArgumentError unless Hash === args
+ raise ArgumentError unless ::Hash === args
raise ArgumentError if args.keys.size != 1 || args.keys.first != :type
raise ArgumentError unless Symbol === args.values.first
end
@type = args.key?(:type) ? args[:type] : DEFAULT_TYPE
- @eye = Hash.new(0)
+ @eye = self.class.const_get( @type.to_s.capitalize ).new
end
- def see(obj)
- true if @eye[obj] += 1
- end
-
- def seen?(obj)
- @eye.key? obj
- end
-end
+ def method_missing(method, *args)
+ @eye.send(method,*args)
+ end
+ class Hash
+ attr_reader :eye
+ def initialize
+ @eye = ::Hash.new(0)
+ end
+ def see(obj)
+ true if @eye[obj] += 1
+ end
+
+ def seen?(obj)
+ @eye.key? obj
+ end
+ end
+
+ class Array
+ attr_reader :eye
+ def initialize
+ @eye = ::Array.new
+ end
+ def see(obj)
+ true if @eye << obj
+ end
+
+ def seen?(obj)
+ @eye.include? obj
+ end
+ end
+
+end
View
@@ -22,18 +22,24 @@
end
it "returns true if .see(obj) has been called previously" do
- ['Kim', 'http://example.com/'].each do |obj|
- @eye.see obj
- @eye.seen?(obj).should == true
+ [:array, :hash].each do |type|
+ eye = Eye.new(:type => type)
+ ['Kim', 'http://example.com/'].each do |obj|
+ eye.see obj
+ eye.seen?(obj).should == true
+ end
+ eye.seen?('Kim').should == true
end
- @eye.seen?('Kim').should == true
end
it "returns false unless .see(obj) has been called previously" do
- ['The Tao of Pooh', 29, 30.3].each do |obj|
- @eye.seen?(obj).should == false
- end
- @eye.seen?(29).should == false
+ [:array, :hash].each do |type|
+ eye = Eye.new(:type => type)
+ ['The Tao of Pooh', 29, 30.3].each do |obj|
+ eye.seen?(obj).should == false
+ end
+ eye.seen?(29).should == false
+ end
end
end
View
@@ -33,10 +33,14 @@
it "causes a Hash to be used as the eye if equal to :hash" do
eye = Eye.new(:type => :hash)
- eye.eye.is_a?(Hash).should == true
+ eye.eye.is_a?(::Hash).should == true
eye = Eye.new
- eye.eye.is_a?(Hash).should == true
+ eye.eye.is_a?(::Hash).should == true
end
+ it "causes an Array to be used as the eye if equal to :array" do
+ eye = Eye.new(:type => :array)
+ eye.eye.is_a?(Array).should == true
+ end
end

0 comments on commit e73827d

Please sign in to comment.