valid_array
The valid_array gem provides to create an Array that enforces certian properties. Each element added to the array is passed to a validator function written by you. This function can raise errors, drop items or change them.
vaild_array also provides compatibility with the typed-array gem. There is both ‘valid_array/typed_array’ which imports to ‘ValidArray::TypedArray` and a fully compatible ’valid-array’ which passes ‘valid-array’s own test suite.
-
Copyright © 2011 Ryan Biesemeyer <[email protected]> (Original typed-array work)
-
Copyright © 2013 Kevin Cox <[email protected]>
-
See LICENSE for details.
Examples
ValidArray
Valid Array provides a hook to change and validate every element added to the array.
require 'valid_array'
# An Array that converts all added elements into strings.
class StringArray < Array
extend ValidArray
def self.validate(element)
element.to_s
end
end
# An array that enforces Numeric types and silently drops odd numbers.
class EvenArray < Array
extend ValidArray
class NotEvenException < Exception
end
def self.validate(element)
if not element.is_a? Numeric
raise TypeError, "Got #{element.class}, expected Numeric!"
end
if element % 2 == 1
# This exception is handled by ValidArray, it causes the element to be
# dropped. All other exceptions are propagated to the caller.
raise ValidArray::DontInsertException
end
end
end
TypedArray
TypedArray is fully compatible with github.com/yaauie/typed-array/. For compatibility mode require ‘typed-array’, otherwise require ‘valid_array/typed_array’ and access it from ‘ValidArray::TypedArray`.
Create Standard Class
require 'typed-array'
class Things < Array
extend TypedArray
restrict_types Thing1,Thing2
end
# or new style
require 'valid_array/typed_array'
class Things < Array
extend ValidArray::TypedArray
restrict_types Thing1,Thing2
end
Generate Class using Factory
require 'typed-array'
things = TypedArray(Thing1,Thing2)
a = things.new
# or new style
require 'valid_array/typed_array'
things = ValidArray::TypedArray(Thing1, Thing2)
a = things.new
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).