Class: TJSON::DataType::Array

Inherits:
NonScalar show all
Defined in:
lib/tjson/datatype/array.rb

Overview

TJSON arrays

Constant Summary

Constants inherited from TJSON::DataType

TAGS

Instance Attribute Summary

Attributes inherited from NonScalar

#inner_type

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from NonScalar

#==, #initialize, #inspect, #scalar?

Methods inherited from TJSON::DataType

[], generate, parse

Constructor Details

This class inherits a constructor from TJSON::DataType::NonScalar

Class Method Details

.identify_type(array) ⇒ Object

Determine the type of a Ruby array (for serialization)



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/tjson/datatype/array.rb', line 8

def self.identify_type(array)
  inner_type = nil

  array.each do |elem|
    t = TJSON::DataType.identify_type(elem)
    inner_type ||= t
    raise TJSON::TypeError, "array contains heterogenous types: #{array.inspect}" unless inner_type == t
  end

  new(inner_type)
end

Instance Method Details

#convert(array) ⇒ Object

Raises:



24
25
26
27
28
29
30
# File 'lib/tjson/datatype/array.rb', line 24

def convert(array)
  raise TJSON::TypeError, "expected Array, got #{array.class}" unless array.is_a?(::Array)

  return array.map! { |o| @inner_type.convert(o) } if @inner_type
  return array if array.empty?
  raise TJSON::ParseError, "no inner type specified for non-empty array: #{array.inspect}"
end

#generate(array) ⇒ Object



32
33
34
# File 'lib/tjson/datatype/array.rb', line 32

def generate(array)
  array.map { |o| TJSON::DataType.generate(o) }
end

#tagObject



20
21
22
# File 'lib/tjson/datatype/array.rb', line 20

def tag
  "A<#{@inner_type.tag}>"
end