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

Constructor Details

#initialize(argv) ⇒ Refactor



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

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

Class Method Details

.optionsObject



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

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

Instance Method Details

#file_string(file) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/lhj/command/refactor_rename.rb', line 60

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



70
71
72
73
74
# File 'lib/lhj/command/refactor_rename.rb', line 70

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

#modify_file(file) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/lhj/command/refactor_rename.rb', line 51

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

#runObject



37
38
39
# File 'lib/lhj/command/refactor_rename.rb', line 37

def run
  update_source_file
end

#update_source_fileObject



41
42
43
44
45
46
47
48
49
# File 'lib/lhj/command/refactor_rename.rb', line 41

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



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

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