class RailwayOperation::Generic::TypedArray

Ensure that only elements of specified type(s) are accepted in the array

Constants

DEFAULT_MESSAGE

Public Class Methods

new(array = [], ensure_type_is:, error_message: nil) click to toggle source
# File lib/railway_operation/generic/typed_array.rb, line 10
def initialize(array = [], ensure_type_is:, error_message: nil)
  raise(ArgumentError, 'must be initialized with an array') unless array.is_a?(Array)

  @types = wrap(ensure_type_is)
  @error_message = error_message || DEFAULT_MESSAGE.(ensure_type_is)
  __setobj__(array)
end

Public Instance Methods

<<(element) click to toggle source
# File lib/railway_operation/generic/typed_array.rb, line 27
def <<(element)
  raise UnacceptableMember, @error_message unless element_acceptable?(element)
  @arr << element
end
__getobj__() click to toggle source
# File lib/railway_operation/generic/typed_array.rb, line 23
def __getobj__
  @arr
end
__setobj__(arr) click to toggle source
# File lib/railway_operation/generic/typed_array.rb, line 18
def __setobj__(arr)
  raise UnacceptableMember, @error_message unless array_acceptable?(arr)
  @arr = arr
end
array_acceptable?(arr) click to toggle source
# File lib/railway_operation/generic/typed_array.rb, line 32
def array_acceptable?(arr)
  arr&.all? { |a| element_acceptable?(a) }
end
element_acceptable?(element) click to toggle source
# File lib/railway_operation/generic/typed_array.rb, line 36
def element_acceptable?(element)
  class_acceptable?(element) || instance_acceptable?(element)
end

Private Instance Methods

class_acceptable?(element) click to toggle source
# File lib/railway_operation/generic/typed_array.rb, line 42
def class_acceptable?(element)
  return false unless element.is_a?(Class)
  @types.detect { |type| element <= type }
end
instance_acceptable?(element) click to toggle source
# File lib/railway_operation/generic/typed_array.rb, line 47
def instance_acceptable?(element)
  @types.detect { |type| element.is_a?(type) }
end
wrap(object) click to toggle source

Taken from ActiveSupport Array.wrap apidock.com/rails/Array/wrap/class

# File lib/railway_operation/generic/typed_array.rb, line 52
def wrap(object)
  if object.respond_to?(:to_ary)
    object.to_ary || [object]
  else
    [object]
  end
end