Class: RFC8259::Object

Inherits:
Value
  • Object
show all
Defined in:
lib/RFC8259/object.rb

Overview

The Objects, as described in RFC8259 section 4.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_ast(ast) ⇒ Object

Parse the AST from parser, and convert into corrsponding values.

Parameters:

  • ast (::Array)

    the AST, generated by the parser

Returns:

  • (Object)

    evaluated instance

Raises:

  • (ArgumentError)

    malformed input



41
42
43
44
45
46
47
48
49
50
# File 'lib/RFC8259/object.rb', line 41

def self.from_ast ast
  type, *assoc = *ast
  raise ArgumentError, "not an object: #{ast.inspect}" if type != :object
  assoc.map! do |a|
    a.map! do |b|
      RFC8259::Value.from_ast b
    end
  end
  new assoc
end

Instance Method Details

#[](key) ⇒ [Value]

Note:

RFC8259 allows identical key to appear multiple times in an object.

Note:

This is O(1)

fetch the key.

Parameters:

  • key (::String, String)

    key to look at

Returns:

  • ([Value])

    corresponding value(s)



57
58
59
60
61
# File 'lib/RFC8259/object.rb', line 57

def [] key
  ret = @assoc.select do |(k, _)| k == key end
  ret.map! do |(_, v)| v end
  return ret
end

#each_pair {|key, value| ... } ⇒ Object Also known as: each

iterates over the pairs.

Yields:

  • (key, value)

    the pair.



65
66
67
68
69
70
71
72
# File 'lib/RFC8259/object.rb', line 65

def each_pair &b
  e = Enumerator.new do |y|
    @assoc.each do |a|
      y << a
    end
  end
  return block_given? ? e.each(&b) : e
end

#inspect::String

Returns the object in string.

Returns:

  • (::String)

    the object in string



96
97
98
99
100
101
102
# File 'lib/RFC8259/object.rb', line 96

def inspect
  hdr = sprintf "#<%p:%#016x {", self.class, self.object_id << 1
  map = @assoc.map do |(k, v)|
    sprintf '%p: %p', k.to_s, v
  end.join ', '
  hdr << map << '}>'
end

#plain_old_ruby_object::Hash Also known as: to_h, to_hash

Returns converted object.

Returns:

  • (::Hash)

    converted object

Raises:

  • (RuntimeError)

    keys conflict



78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/RFC8259/object.rb', line 78

def plain_old_ruby_object
  ret = Hash.new
  @assoc.each do |(k, v)|
    kk = k.plain_old_ruby_object
    if ret.include? kk
      raise RuntimeError, "key #{kk} conflict."
    else
      vv = v.plain_old_ruby_object
      ret.store kk, vv
    end
  end
  return ret
end

#pretty_print(pp) ⇒ Object

For pretty print

Parameters:

  • pp (PP)

    the pp



106
107
108
109
110
111
112
113
114
115
116
# File 'lib/RFC8259/object.rb', line 106

def pretty_print pp
  hdr = sprintf '#<%p:%#016x', self.class, self.object_id << 1
  pp.group 1, hdr, '>' do
    pp.text ' '
    RFC8259::Dumper.kandr pp, 1, @assoc.each, '{', '}' do |(i, j)|
      i.pretty_print pp
      pp.text ': '
      j.pretty_print pp
    end
  end
end