Module: Jimmy::Json::Collection

Includes:
Enumerable
Included in:
Array, Hash
Defined in:
lib/jimmy/json/collection.rb

Overview

Common methods for Hash and Array

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object

Get the member of the collection assigned to the given key.



33
34
35
# File 'lib/jimmy/json/collection.rb', line 33

def [](key)
  @members[cast_key(key)]
end

#as_json(id: '', index: {}) ⇒ Hash, Array

Transform the collection into plain JSON-compatible objects.

Returns:



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/jimmy/json/collection.rb', line 47

def as_json(id: '', index: {})
  return index[object_id].as_json(id: id, index: {}) if index[object_id]

  id = Json::URI.new(id)
  index[object_id] = Jimmy.ref(id)

  pairs = map do |key, value|
    if value.respond_to? :as_json
      value = value.as_json(id: id / key, index: index)
    end
    [key, value]
  end

  export_pairs pairs
end

#clearself

Removes all members.

Returns:

  • (self)


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

def clear
  @members.clear
  self
end

#deep_dup(index = {}) ⇒ Jimmy::Json::Collection

Duplicate the collection and all of its members, recursively.



78
79
80
81
82
# File 'lib/jimmy/json/collection.rb', line 78

def deep_dup(index = {})
  return index[object_id] if index.key? object_id

  deep_dup_enumerable(self, index) { |new, k, v| new[k] = v }
end

#dig(key, *rest) ⇒ Object

See Also:



38
39
40
41
42
43
# File 'lib/jimmy/json/collection.rb', line 38

def dig(key, *rest)
  obj = self[cast_key(key)]
  return obj if obj.nil? || rest.empty?

  obj.dig(*rest)
end

#dupJimmy::Json::Collection

Duplicate the collection.



72
73
74
# File 'lib/jimmy/json/collection.rb', line 72

def dup
  self.class.new @members
end

#empty?true, false

Returns true if the collection has no members.

Returns:

  • (true, false)


21
22
23
# File 'lib/jimmy/json/collection.rb', line 21

def empty?
  @members.empty?
end

#freezeself

Freeze the collection.

Returns:

  • (self)


27
28
29
30
# File 'lib/jimmy/json/collection.rb', line 27

def freeze
  @members.freeze
  super
end

#inspectObject

See Also:

  • Object#inspect


15
16
17
# File 'lib/jimmy/json/collection.rb', line 15

def inspect
  to_json
end

#to_json(**opts) ⇒ Object

Serialize the collection as JSON.



10
11
12
# File 'lib/jimmy/json/collection.rb', line 10

def to_json(**opts)
  JSON.generate as_json, **opts
end