I am creating a base collection class that will allow the assignment of
multiple code blocks which validate the addition of objects to the
collection. The code looks like this:
<< Code Snippet >>
class CollectionBase
public
def initialize()
@validators = Array.new() # Contains any validators
@items = Array.new() # Contains collection’s objects
end
# Adds a code block to the validators array that will be called when
adding
# items to the collection.
def add_validator(&block)
validators.push(block)
end
# Adds an object to the collection
def add(obj)
# Check to see if the object is valid for this collection
if valid?(obj)
@items.push(obj)
return @items.length - 1
end
end
… Code omitted to be consise
# Loops through all validators and passes the
# object being checked to the code block.
# If any validator returns false the object is
# invalid.
def valid?(obj)
invalid = false
@validators.each do |validator|
if !validator.nil?
invalid = true if !validator.call(obj)
end
end
!invalid
end
end
<< End Code Snippet >>
This code works fine. I can create a new CollectionBase, pass a code
block to add_validators and depending on the result of the code block
objects are added or not.
The problem comes when I try and subclass this class. I also want to
create a SetBase class which extends CollectionBase but by default adds
a validator that prevents duplicate objects from being added:
<< Code Snippet >>
require ‘Collections’
class SetBase < CollectionBase
public
def initialize()
super
# add a validator that returns false if object is already
# in the set
add_validator {return !index(obj) }
end
end
<< End Code Snippet >>
When I try to add an item to SetBase, however, I get the error:
unexpected return (LocalJumpError)
I have stepped through with a debugger and the error is raised when an
attempt is made to call the code block (ie. the addition of the
validator works fine).
Does anyone have any idea why this is happening?
Thanks,
Aaron