Class: Rfactor::Code

Inherits:
Object
  • Object
show all
Defined in:
lib/rfactor/code.rb

Instance Method Summary collapse

Constructor Details

#initialize(code) ⇒ Code

Returns a new instance of Code.



5
6
7
8
9
# File 'lib/rfactor/code.rb', line 5

def initialize(code)
  @code = code
  @ast = RubyParser.new.parse(code)
  @line_finder = LineFinder.new(@ast)
end

Instance Method Details

#extract_method(args) ⇒ Object



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
# File 'lib/rfactor/code.rb', line 11

def extract_method(args)
  raise ":name is required" unless args.has_key?(:name)
  
  method_lines = @line_finder.method_lines(args[:start])
  selected_lines = Range.new(args[:start], args[:end])
  
  new_code = ""
  extracted_method = ""
  added = false
  identation = 0
  
  @code.each_with_index do |line, n|
    line_number = n + 1 # not 0-based
    if line_number == method_lines.first
      identation = extract_identation_level_from line
      extracted_method << "\n#{identation}"
      extracted_method << "def #{args[:name]}()\n"
    end
    if selected_lines.include? line_number
      new_code << "#{identation}  #{args[:name]}()\n" if line_number == selected_lines.first
      extracted_method << line
    elsif line_number > method_lines.last && !added
      added = true
      new_code << extracted_method << "#{identation}end\n"
      new_code << line
    else
      new_code << line
    end
  end
  new_code << "\n#{extracted_method}#{identation}end\n" unless added
  new_code
end