0.0
No commit activity in last 3 years
No release in over 3 years
All methods that alter the contents of an array that implements this Gem are first checked to ensure that the added items are of the types allowed. All methods behave exactly as their Array counterparts, including additional forms, block processing, etc.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.0
~> 1.6
~> 3.9
~> 2.6
 Project Readme

valid_array¶ ↑

<img src=“https://travis-ci.org/kevincox/valid_array.png” alt=“Build Status”/>

The valid_array gem provides to create an Array that enforces certain 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.

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

  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 you can require ‘typed-array’, otherwise require ‘valid_array/typed_array’ and access it from ‘ValidArray::TypedArray`.

Create Standard Class¶ ↑

# Compatibility style.
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¶ ↑

# Compatibility style.
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).