/
action.rb
46 lines (41 loc) · 1.25 KB
/
action.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# frozen_string_literal: true
module Synvert::Core
# Action defines rewriter action, add, replace or remove code.
class Rewriter::Action
DEFAULT_OPTIONS = { autoindent: true }
DEFAULT_INDENT = 2
# Initialize an action.
#
# @param instance [Synvert::Core::Rewriter::Instance]
# @param code [String] new code to add, replace or remove.
# @param options [Hash] action options, it includes :autoindent.
def initialize(instance, code, options = {})
@instance = instance
@code = code
@options = DEFAULT_OPTIONS.merge(options)
@node = @instance.current_node
end
# Line number of current node.
#
# @return [Integer] line number.
def line
@node.loc.expression.line
end
# The rewritten source code with proper indent.
#
# @return [String] rewritten code.
def rewritten_code
if rewritten_source.split("\n").length > 1
"\n\n" + rewritten_source.split("\n").map { |line| indent(@node) + line }.join("\n")
else
"\n" + indent(@node) + rewritten_source
end
end
# The rewritten source code.
#
# @return [String] rewritten source code.
def rewritten_source
@rewritten_source ||= @node.rewritten_source(@code)
end
end
end