Class: NRSER::Types::ArrayType

Inherits:
IsA
  • Object
show all
Defined in:
lib/nrser/types/array.rb

Direct Known Subclasses

ArrayOfType, TupleType

Constant Summary collapse

DEFAULT_SPLIT_WITH =

Default value to split strings with in #from_s if the string provided does is not recognized as an encoding format (as of writing, JSON is the only format we attempt to detect).

Splits

/\,\s*/m

Instance Attribute Summary collapse

Attributes inherited from IsA

#klass

Instance Method Summary collapse

Methods inherited from IsA

#from_data, #has_from_data?, #test

Methods inherited from Type

#check, #from_data, #has_from_data?, #has_from_s?, #has_to_data?, #name, #respond_to?, short_name, #test, #to_data, #to_s

Constructor Details

#initialize(split_with: DEFAULT_SPLIT_WITH, **options) ⇒ ArrayType

Returns a new instance of ArrayType.



44
45
46
47
# File 'lib/nrser/types/array.rb', line 44

def initialize split_with: DEFAULT_SPLIT_WITH, **options
  super ::Array, **options
  @split_with = split_with
end

Instance Attribute Details

#item_typeObject (readonly)

Returns the value of attribute item_type.



42
43
44
# File 'lib/nrser/types/array.rb', line 42

def item_type
  @item_type
end

Instance Method Details

#default_nameObject



50
51
52
# File 'lib/nrser/types/array.rb', line 50

def default_name
  self.class.short_name
end

#from_s(s) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/nrser/types/array.rb', line 76

def from_s s
  # Use custom {@from_s} if we have one.
  return check( @from_s.call s ) unless @from_s.nil?
  
  # Does it looks like a JSON array?
  if NRSER.looks_like_json_array? s
    # It does! Load it
    begin
      array = JSON.load( s )
    rescue
      # pass - if we failed to load as JSON, it may just not be JSON, and
      # we can try the split approach below.
    else
      # Check value and return. If we fail the check here let the error
      # bubble up
      return check array
    end
  end
  
  # Split it with the splitter and check that
  check items_from_strings( s.split( @split_with ) )
end

#items_from_strings(items) ⇒ Array

Called on an array of string items that have been split from a single string by #from_s to convert each individual item before Type#check is called on the value.

NRSER::Types::ArrayType implementation is a no-op that just returns ‘items` - this method is in place for subclasses to override.

Parameters:

  • items (Array<String>)

Returns:

  • (Array)


71
72
73
# File 'lib/nrser/types/array.rb', line 71

def items_from_strings items
  items
end