Class: Prosereflect::Transform::InsertStep

Inherits:
Step
  • Object
show all
Defined in:
lib/prosereflect/transform/insert_step.rb

Overview

Insert content at a position

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Step

#merge, #to

Constructor Details

#initialize(pos, content) ⇒ InsertStep

Returns a new instance of InsertStep.



14
15
16
17
18
# File 'lib/prosereflect/transform/insert_step.rb', line 14

def initialize(pos, content)
  super()
  @pos = pos
  @content = content.is_a?(Fragment) ? content : Fragment.new(content)
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



12
13
14
# File 'lib/prosereflect/transform/insert_step.rb', line 12

def content
  @content
end

#posObject (readonly)

Returns the value of attribute pos.



12
13
14
# File 'lib/prosereflect/transform/insert_step.rb', line 12

def pos
  @pos
end

Class Method Details

.from_json(_schema, json) ⇒ Object



52
53
54
55
# File 'lib/prosereflect/transform/insert_step.rb', line 52

def self.from_json(_schema, json)
  content = (json["content"] || []).map { |h| Prosereflect::Node.from_h(h) }
  new(json["pos"], Fragment.new(content))
end

Instance Method Details

#apply(doc) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/prosereflect/transform/insert_step.rb', line 20

def apply(doc)
  return Result.fail("Invalid position") if @pos.negative? || @pos > doc.node_size

  begin
    slice = Slice.new(@content)
    replace_step = ReplaceStep.new(@pos, @pos, slice)
    replace_step.apply(doc)
  rescue StandardError => e
    Result.fail(e.message)
  end
end

#get_mapObject



32
33
34
35
# File 'lib/prosereflect/transform/insert_step.rb', line 32

def get_map
  delta = @content.size
  StepMap.new([[@pos, @pos, @pos, @pos + delta]])
end

#invert(_doc) ⇒ Object



37
38
39
# File 'lib/prosereflect/transform/insert_step.rb', line 37

def invert(_doc)
  DeleteStep.new(@pos, @pos + @content.size)
end

#step_typeObject



41
42
43
# File 'lib/prosereflect/transform/insert_step.rb', line 41

def step_type
  "insert"
end

#to_json(*_args) ⇒ Object



45
46
47
48
49
50
# File 'lib/prosereflect/transform/insert_step.rb', line 45

def to_json(*_args)
  json = super
  json["pos"] = @pos
  json["content"] = @content.to_a.map(&:to_h)
  json
end