Class: JSONP3::RelativeJSONPointer

Inherits:
Object
  • Object
show all
Defined in:
lib/json_p3/pointer.rb

Overview

Constant Summary collapse

RE_RELATIVE_POINTER =
/\A(?<ORIGIN>\d+)(?<INDEX_G>(?<SIGN>[+-])(?<INDEX>\d))?(?<POINTER>.*)\z/m
RE_INT =
/\A(0|[1-9][0-9]*)\z/

Instance Method Summary collapse

Constructor Details

#initialize(rel) ⇒ RelativeJSONPointer

Returns a new instance of RelativeJSONPointer.

Parameters:

  • rel (String)

Raises:

[View source]

181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/json_p3/pointer.rb', line 181

def initialize(rel)
  match = RE_RELATIVE_POINTER.match(rel)

  raise JSONPointerSyntaxError, "failed to parse relative pointer" if match.nil?

  @origin = parse_int(match[:ORIGIN] || raise)
  @index = 0

  if match[:INDEX_G]
    @index = parse_int(match[:INDEX] || raise)
    raise JSONPointerSyntaxError, "index offset can't be zero" if @index.zero?

    @index = -@index if match[:SIGN] == "-"
  end

  @pointer = match[:POINTER] == "#" ? "#" : JSONPointer.new(match[:POINTER] || raise)
end

Instance Method Details

#to(pointer) ⇒ JSONPointer

Return a new JSON Pointer by applying this relative pointer to pointer.

Parameters:

Returns:

Raises:

[View source]

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/json_p3/pointer.rb', line 208

def to(pointer)
  p = pointer.is_a?(String) ? JSONPointer.new(pointer) : pointer

  raise JSONPointerIndexError, "origin (#{@origin}) exceeds root (#{p.tokens.length})" if @origin > p.tokens.length

  tokens = @origin < 1 ? p.tokens[0..] || raise : p.tokens[0...-@origin] || raise
  tokens[-1] = (tokens[-1] || raise) + @index if @index != 0 && tokens.length.positive? && tokens[-1].is_a?(Integer)

  if @pointer == "#"
    tokens[-1] = "##{tokens[-1]}"
  else
    tokens.concat(@pointer.tokens) # steep:ignore
  end

  JSONPointer.new(JSONPointer.encode(tokens))
end

#to_sObject

[View source]

199
200
201
202
203
# File 'lib/json_p3/pointer.rb', line 199

def to_s
  sign = @index.positive? ? "+" : ""
  index = @index.zero? ? "" : "#{sign}#{@index}"
  "#{@origin}#{index}#{@pointer}"
end