Class: Astel::Rewriter
- Inherits:
-
Object
show all
- Defined in:
- lib/astel/rewriter.rb
Defined Under Namespace
Classes: ConflictError, Edit, EditIndex
Instance Method Summary
collapse
Constructor Details
#initialize(source_file) ⇒ Rewriter
Returns a new instance of Rewriter.
82
83
84
85
86
87
88
89
|
# File 'lib/astel/rewriter.rb', line 82
def initialize(source_file)
@source_file = source_file
@edits = []
@edits_snapshot = nil
@edit_index = EditIndex.new
@sequence = 0
@result_size_delta = 0
end
|
Instance Method Details
#edits ⇒ Object
91
92
93
|
# File 'lib/astel/rewriter.rb', line 91
def edits
@edits_snapshot ||= @edits.dup.freeze
end
|
#insert_after(location, content) ⇒ Object
105
106
107
108
|
# File 'lib/astel/rewriter.rb', line 105
def insert_after(location, content)
_, end_offset = offsets(location)
add_edit(end_offset, end_offset, content)
end
|
#insert_before(location, content) ⇒ Object
100
101
102
103
|
# File 'lib/astel/rewriter.rb', line 100
def insert_before(location, content)
start_offset, = offsets(location)
add_edit(start_offset, start_offset, content)
end
|
#remove(location) ⇒ Object
110
111
112
|
# File 'lib/astel/rewriter.rb', line 110
def remove(location)
replace(location, '')
end
|
#replace(location, replacement) ⇒ Object
95
96
97
98
|
# File 'lib/astel/rewriter.rb', line 95
def replace(location, replacement)
start_offset, end_offset = offsets(location)
add_edit(start_offset, end_offset, replacement)
end
|
#rewrite ⇒ Object
114
115
116
117
118
119
120
121
122
123
124
125
126
127
|
# File 'lib/astel/rewriter.rb', line 114
def rewrite
source = @source_file.source
result = String.new(capacity: source.bytesize + @result_size_delta, encoding: source.encoding)
cursor = 0
@edit_index.each do |edit|
result << source.byteslice(cursor, edit.start_offset - cursor)
result << edit.replacement
cursor = edit.end_offset
end
result << source.byteslice(cursor, source.bytesize - cursor)
result
end
|