Class: ThorTemplate::Renamer

Inherits:
Object
  • Object
show all
Defined in:
lib/thor_template/renamer.rb

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Renamer

Returns a new instance of Renamer.



3
4
5
# File 'lib/thor_template/renamer.rb', line 3

def initialize(name)
  @name = name
end

Instance Method Details

#empty_directoriesObject



61
62
63
64
65
# File 'lib/thor_template/renamer.rb', line 61

def empty_directories
  Dir['**/*'].
    select { |d| File.directory? d }.
    select { |d| (Dir.entries(d) - %w[ . .. ]).empty? }.to_a
end

#remove_empty_directoriesObject



55
56
57
58
59
# File 'lib/thor_template/renamer.rb', line 55

def remove_empty_directories
  until empty_directories.empty?
    empty_directories.each { |d| Dir.rmdir(d) }
  end
end

#rename!Object



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/thor_template/renamer.rb', line 7

def rename!
  Dir.chdir(@name) do
    Dir.glob("**/*") do |path|
      next unless File.file?(path)
      rename_content(path)

      next unless File.file?(path)
      rename_path(path)
    end # Dir.glob

    remove_empty_directories
  end
end

#rename_content(path) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/thor_template/renamer.rb', line 21

def rename_content(path)
  content = IO.readlines(path)
  result = content.map do |line|
    line = line.gsub(/ThorTemplate/, @name.underscore.camelize)
    line = line.gsub(/thor_template/, @name.underscore)
    line = line.gsub("USER_PROVIDED_NAME", @name) # special case
    line
  end
  IO.write(path, result.join(''))
end

#rename_path(src) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/thor_template/renamer.rb', line 32

def rename_path(src)
  dest = special_rename?(src) ?
    src.gsub(/thor_template/, @name) :
    src.gsub(/thor_template/, @name.underscore)

  folder = File.dirname(dest)
  FileUtils.mkdir_p(folder) unless File.exist?(folder)

  FileUtils.mv(src, dest) unless src == dest
end

#special_rename?(path) ⇒ Boolean

These paths should be rename with the actually named provied by the user, the the underscored version.

Returns:

  • (Boolean)


45
46
47
48
49
50
51
# File 'lib/thor_template/renamer.rb', line 45

def special_rename?(path)
  %w[
    thor_template.gemspec
    exe/thor_template
    lib/thor_template.rb
  ].include?(path)
end