1
+ namespace :haml do
2
+ task :erb_2_haml do
3
+
4
+ puts "This task will generate a .html.haml translation of each of the .html.erb files in app/views and its subdirectories."
5
+
6
+ erb_files = Dir . glob ( 'app/views/**/*.erb' ) . select { |f | File . file? f }
7
+ haml_files = Dir . glob ( 'app/views/**/*.haml' ) . select { |f | File . file? f }
8
+
9
+ if erb_files . empty?
10
+ puts "No .erb files found. Task will now exit."
11
+ exit
12
+ end
13
+
14
+ haml_files_w_out_ext = haml_files . map { |f | f . gsub ( /\. haml\z / , '' ) }
15
+
16
+ # Get a list of all those erb files that already seem to have .haml equivalents
17
+
18
+ already_existing = erb_files . select { |f | short = f . gsub ( /\. erb\z / , '' ) ; haml_files_w_out_ext . include? ( short ) }
19
+
20
+ puts '-' *80
21
+
22
+ if already_existing . any?
23
+ puts "Some of your .html.erb files seem to already have .haml equivalents:"
24
+ already_existing . map { |f | puts "\t #{ f } " }
25
+
26
+ # Ask the user whether he/she would like to overwrite them.
27
+ begin
28
+ puts "Would you like to overwrite these .haml files? (y/n)"
29
+ should_overwrite = STDIN . gets . chomp . downcase [ 0 ]
30
+ end until [ 'y' , 'n' ] . include? ( should_overwrite )
31
+ puts '-' *80
32
+
33
+ # If we are not overwriting, remove each already_existing from our erb_files list
34
+ if should_overwrite == 'n'
35
+ erb_files = erb_files - already_existing
36
+
37
+ if erb_files . empty?
38
+ # It is possible no .erb files remain, after we remove already_existing
39
+ puts "No .erb files remain. Task will now exit."
40
+ return
41
+ end
42
+ else
43
+ # Delete the current .haml
44
+ already_existing . each { |f | File . delete ( f . gsub ( /\. erb\z / , '.haml' ) ) }
45
+ end
46
+ end
47
+
48
+ erb_files . each do |file |
49
+ puts "Generating HAML for #{ file } ..."
50
+ `html2haml #{ file } #{ file . gsub ( /\. erb\z / , '.haml' ) } `
51
+ end
52
+
53
+ puts '-' *80
54
+
55
+ puts "HAML generated for the following files:"
56
+ erb_files . each do |file |
57
+ puts "\t #{ file } "
58
+ end
59
+
60
+ puts '-' *80
61
+ begin
62
+ puts 'Would you like to delete the original .erb files? (This is not recommended unless you are under version control.) (y/n)'
63
+ should_delete = STDIN . gets . chomp . downcase [ 0 ]
64
+ end until [ 'y' , 'n' ] . include? ( should_delete )
65
+
66
+ if should_delete == 'y'
67
+ puts "Deleting original .erb files."
68
+ File . delete *erb_files
69
+ else
70
+ puts "Please remember to delete your .erb files once you have ensured they were translated correctly."
71
+ end
72
+
73
+ puts '-' *80
74
+ puts "Task complete!"
75
+ end
76
+ end
0 commit comments