valid-array
Gem provides enforced-properties to arrays.
Copyright © 2011 Ryan Biesemeyer Copyright © 2013 Kevin Cox See LICENSE.txt for details
Ryan Biesemeyer [email protected] Ryan Biesemeyer [email protected]
Example
ValidArray
Valid Array provides a hook to change and validate every element added to the array.
require 'valid-array'
class StringArray < Array
extend ValidArray
def self.validate(element)
element.to_s # Make everything a String.
end
end
class EvenArray < Array
extend ValidArray
def self.validate(element)
if not element.is_a? Numeric
raise UnexpectedTypeException([Numeric], element.class)
end
if element % 2 == 1
# Assuming this exception is defined somewhere.
raise NotEvenException(element)
end
end
end
TypedArray
TypedArray is fully compatible with github.com/yaauie/typed-array/.
Create Standard Class
require 'typed-array'
class Things < Array
extend TypedArray
restrict_types Thing1,Thing2
end
Generate Class using Factory
require 'typed-array'
things = TypedArray(Thing1,Thing2)
Adding items to the Array
# All standard Array interfaces are implemented, including block-processing
# and variable-number of arguments. For methods that would usually return an
# Array, they instead return an instance of the current class (except to_a).
#
# The difference is that if the method would generate an Array including the
# wrong types, ValidArray::UnexpectedTypeException is raised and the call is
# aborted before modifying the enforced ValidArray instance.
require 'typed-array'
symbols = TypedArray(Symbol).new([:foo,:bar,:baz,:bingo])
begin
integers = TypedArray(Integer).new([1,3,7,2,:symbol])
rescue TypedArray::UnexpectedTypeException
puts "An error occured: #{$!}"
end