Advertisement
Guest User

Untitled

a guest
Dec 8th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. CHARS = [*'A'..'Z', *'a'..'z']
  2.  
  3. def index_to_shortcut(number, base = 52)
  4. quotient, remainder = number.divmod(base)
  5.  
  6. if quotient.zero?
  7. CHARS[remainder]
  8. else
  9. index_to_shortcut(quotient - 1, base) + CHARS[remainder]
  10. end
  11. end
  12.  
  13. def log_size(original, minified)
  14. original_size = File.size(original)
  15. minified_size = File.size(minified)
  16. ratio = (100.0 * (original_size - minified_size) / original_size).round(2)
  17.  
  18. puts "#{original}"
  19. puts "\t#{(original_size / 1024.0).round(2)}KB ➔ #{(minified_size / 1024.0).round(2)}KB"
  20. puts "\t#{ratio}% compressed.\n\n"
  21. end
  22.  
  23. def make_map(selectors, shortcuts)
  24. contents = ''
  25.  
  26. selectors.each_with_index do |value, index|
  27. contents << "#{index + 1}\t#{shortcuts[index]}\t#{value}\n"
  28. end
  29.  
  30. File.write('map.txt', contents)
  31. end
  32.  
  33. selectors = []
  34. shortcuts = []
  35.  
  36. html_files = ['lezhin.html']
  37. css_path = File.join('./lezhin_files', '*.css')
  38. css_files = Dir.glob(css_path)
  39.  
  40. css_files.each do |filename|
  41. simple_css= File.read(filename).gsub(/{[^}]+}/, '{}')
  42. candidates = simple_css.scan(/(?<=[#.])[a-z]{1}[a-z0-9\-_]*/i).reject{|selector| selector.size < 3}
  43. selectors.concat(candidates)
  44. end
  45.  
  46. selectors.uniq!.sort_by!{|x| [-x.length, x]}
  47.  
  48. puts "#{selectors.size} selectors found.\n\n"
  49.  
  50. selectors.each_with_index do |value, index|
  51. shortcuts << index_to_shortcut(index)
  52. end
  53.  
  54. html_files.each do |filename|
  55. contents = File.read(filename)
  56. contents.gsub!(/^\s+/, '').gsub!(/\r?\n/, '')
  57.  
  58. selectors.each_with_index do |value, index|
  59. contents.gsub!(/(?<!<)#{value}/, shortcuts[index])
  60. end
  61.  
  62. new_filename = filename.gsub(/\.html$/, '.min.html')
  63. File.write(new_filename, contents)
  64.  
  65. log_size(filename, new_filename)
  66. end
  67.  
  68. css_files.each do |filename|
  69. contents = File.read(filename)
  70. selectors.each_with_index do |value, index|
  71. contents.gsub!(/([#.]{1})#{value}/, '\1' + shortcuts[index])
  72. end
  73.  
  74. new_filename = filename.gsub(/\.css$/, '.min.css')
  75. File.write(new_filename, contents)
  76.  
  77. log_size(filename, new_filename)
  78. end
  79.  
  80. make_map(selectors, shortcuts)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement