Class: Lhj::Command::Refactor

Inherits:
Lhj::Command
  • Object
show all
Defined in:
lib/lhj/command/refactor_rename.rb

Overview

refactor global name

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Lhj::Command

#auto_spin, #begin_title, #run, #stop

Constructor Details

#initialize(argv) ⇒ Refactor

Returns a new instance of Refactor.



31
32
33
34
35
36
37
# File 'lib/lhj/command/refactor_rename.rb', line 31

def initialize(argv)
  @current_path = argv.shift_argument || Dir.pwd
  @key = argv.option('key')
  @other = argv.option('other')
  @modify_files = []
  super
end

Class Method Details

.optionsObject



18
19
20
21
22
23
# File 'lib/lhj/command/refactor_rename.rb', line 18

def self.options
  [
    %w[--key 变量名],
    %w[--other 新的变量名]
  ]
end

Instance Method Details

#file_string(file) ⇒ Object



65
66
67
68
69
70
71
72
73
# File 'lib/lhj/command/refactor_rename.rb', line 65

def file_string(file)
  str = ''
  File.open(file, 'r+') do |f|
    f.each_line do |line|
      str += format_string(f, line)
    end
  end
  str
end

#format_string(file, line) ⇒ Object



75
76
77
78
79
80
81
82
# File 'lib/lhj/command/refactor_rename.rb', line 75

def format_string(file, line)
  result = line
  if /(\W)(#{@key})(\W)/ =~ line
    result = result.gsub(/(\W)(#{@key})(\W)/, "\\1#{@other}\\3")
    @modify_files << file unless @modify_files.include?(file)
  end
  result
end

#handleObject



39
40
41
42
# File 'lib/lhj/command/refactor_rename.rb', line 39

def handle
  update_source_file
  print_info
end

#modify_file(file) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/lhj/command/refactor_rename.rb', line 54

def modify_file(file)
  File.chmod(0o644, file)
  # arr = File.open(file, 'r+').readlines
  # lines = arr.size
  str = file_string(file)
  File.open(file, 'w+') do |f|
    f.write(str)
  end
  File.chmod(0o444, file) if file =~ /Pods/
end


84
85
86
87
88
89
90
91
92
# File 'lib/lhj/command/refactor_rename.rb', line 84

def print_info
  rows = []
  @modify_files.each do |file|
    rows << [File.basename(file), File.absolute_path(file)]
  end
  title = "修改了#{rows.count}个文件"
  table = Terminal::Table.new title: title, headings: %w[文件 路径], rows: rows
  puts table
end

#update_source_fileObject



44
45
46
47
48
49
50
51
52
# File 'lib/lhj/command/refactor_rename.rb', line 44

def update_source_file
  Dir.glob("#{@current_path}/**/*.{m,h,pch}").each do |f|
    if f =~ /Pods/
      modify_file(f) if f =~ %r{Pods/ML}
    else
      modify_file(f)
    end
  end
end

#validate!Object



25
26
27
28
29
# File 'lib/lhj/command/refactor_rename.rb', line 25

def validate!
  super
  help! '输入变量名' unless @key
  help! '新的变量名' unless @other
end