Class: JSONP3::OpReplace

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

Overview

The JSON Patch replace operation.

Instance Method Summary collapse

Constructor Details

#initialize(pointer, value) ⇒ OpReplace

Returns a new instance of OpReplace.

Parameters:

[View source]

126
127
128
129
130
# File 'lib/json_p3/patch.rb', line 126

def initialize(pointer, value)
  super()
  @pointer = pointer
  @value = value
end

Instance Method Details

#apply(value, index) ⇒ Object

[View source]

136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/json_p3/patch.rb', line 136

def apply(value, index)
  parent, obj = @pointer.resolve_with_parent(value)
  return @value if parent == JSONP3::JSONPointer::UNDEFINED && @pointer.tokens.empty?

  if parent == JSONP3::JSONPointer::UNDEFINED
    raise JSONPatchError,
          "no such property or item '#{@pointer.parent}' (#{name}:#{index})"
  end

  target = @pointer.tokens.last
  if target == JSONP3::JSONPointer::UNDEFINED
    raise JSONPatchError,
          "unexpected operation (#{name}:#{index})"
  end

  if parent.is_a?(Array)
    raise JSONPatchError, "no item to replace (#{name}:#{index})" if obj == JSONP3::JSONPointer::UNDEFINED

    parent[target.to_i] = @value
  elsif parent.is_a?(Hash)
    raise JSONPatchError, "no property to replace (#{name}:#{index})" if obj == JSONP3::JSONPointer::UNDEFINED

    parent[target] = @value
  else
    raise JSONPatchError, "unexpected operation on #{parent.class} (#{name}:#{index})"
  end

  value
end

#nameObject

[View source]

132
133
134
# File 'lib/json_p3/patch.rb', line 132

def name
  "replace"
end

#to_hObject

[View source]

166
167
168
# File 'lib/json_p3/patch.rb', line 166

def to_h
  { "op" => name, "path" => @pointer.to_s, "value" => @value }
end