Module: ValidArray::TypedArray

Defined in:
lib/valid_array/typed_array.rb

Overview

Provides ValidArray functionality to a subclass of Array when extended in the class’s definiton

Defined Under Namespace

Classes: UnexpectedTypeException

Instance Method Summary collapse

Instance Method Details

#inherited(subclass) ⇒ Object

when a class inherits from this one, make sure that it also inherits the types that are being enforced



11
12
13
14
# File 'lib/valid_array/typed_array.rb', line 11

def inherited(subclass)
  self._subclasses << subclass
  subclass.restricted_types *self.restricted_types
end

#restricted_types(*types) ⇒ Object Also known as: restricted_type

A getter/setter for types to add. If no arguments are passed, it simply returns the current array of accepted types.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/valid_array/typed_array.rb', line 18

def restricted_types(*types)
  @_restricted_types ||= []
  types.each do |type|
    raise UnexpectedTypeException.new([Class],type.class) unless type.is_a? Class
    @_restricted_types << type unless @_restricted_types.include? type
    _subclasses.each do |subclass|
      subclass.restricted_types type
    end
  end
  @_restricted_types
end

#validate(item) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/valid_array/typed_array.rb', line 46

def validate(item)
  if item.nil? or restricted_types.any? { |allowed| item.class <= allowed }
    return item
  else
    raise TypedArray::UnexpectedTypeException.new(restricted_types, item.class)
  end
end