Class: Jimmy::Json::Array

Inherits:
Object
  • Object
show all
Includes:
Collection
Defined in:
lib/jimmy/json/array.rb

Overview

Represents an array in a JSON schema.

Constant Summary collapse

KEY_PATTERN =
/\A(?:\d|[1-9]\d+)\z/.freeze

Instance Method Summary collapse

Methods included from Collection

#[], #as_json, #clear, #empty?, #freeze, #inspect, #to_json

Constructor Details

#initialize(array = []) ⇒ Array

Returns a new instance of Array.

Parameters:

  • array (Array, ::Array, Set) (defaults to: [])

    Items to be included in the array.



14
15
16
17
18
# File 'lib/jimmy/json/array.rb', line 14

def initialize(array = [])
  super()
  @members = []
  concat array
end

Instance Method Details

#concat(array) ⇒ self

Append items in array to self.

Parameters:

  • array (Array, ::Array, Set)

Returns:

  • (self)


23
24
25
26
# File 'lib/jimmy/json/array.rb', line 23

def concat(array)
  array = array.to_a if array.is_a? Set
  push *array
end

#dig(key, *rest) ⇒ Object

Dig into the array.

Parameters:

  • key (Integer)

    Index of the item to be dug or returned.

  • rest (Array<String, Integer>)

    Keys or indexes to be passed to resolved hashes/arrays.



65
66
67
68
# File 'lib/jimmy/json/array.rb', line 65

def dig(key, *rest)
  key = key.to_i if key.is_a?(String) && key.match?(KEY_PATTERN)
  super key, *rest
end

#each {|index, member| ... } ⇒ Enumerable, self

Iterate over items in the array. If a block with a single argument is given, only values will be yielded. Otherwise, indexes and values will be yielded.

Yield Parameters:

  • index (Integer)

    The index of each item.

  • member (Object)

    Each item.

Returns:

  • (Enumerable, self)

    If no block is given, an Enumerable is returned. Otherwise, self is returned.



45
46
47
48
49
50
51
52
53
54
# File 'lib/jimmy/json/array.rb', line 45

def each(&block)
  return enum_for :each unless block

  if block.arity == 1
    @members.each { |member| yield member }
  else
    @members.each.with_index { |member, i| yield i, member }
  end
  self
end

#lengthInteger Also known as: count, size

Returns The length of the array.

Returns:

  • (Integer)

    The length of the array.



57
58
59
# File 'lib/jimmy/json/array.rb', line 57

def length
  @members.length
end

#push(*members) ⇒ self Also known as: <<

Add one or more items to self.

Parameters:

  • members (Array)

    Things to add.

Returns:

  • (self)


31
32
33
34
# File 'lib/jimmy/json/array.rb', line 31

def push(*members)
  @members.concat members.map(&method(:cast_value))
  self
end

#to_aArray

Returns Get a regular array.

Returns:

  • (Array)

    Get a regular array.



71
72
73
# File 'lib/jimmy/json/array.rb', line 71

def to_a
  @members.dup
end