Posted By

lfatr on 01/29/13


Tagged

script ruby open-uri gems nokogiri


Versions (?)

001: Parse and add a CSS class to every html file in a folder


 / Published in: Ruby
 

URL: www.larsattacks.co.uk

Run from console: ruby {filename} Careful this script does not only read but also write

This script - looks for every html file in the folder above - parses them and generates a classname based on the file name ( '019-5028dca6d8bd8861270001b1.html' -> 'page19' ) - checks if the page's body tag has the page class, adds the class to the body tag - and writes it back

LA

  1. # This ruby script loads all .html files in the folder above, check for a class
  2. # on the body, generate a class from the filename ( i.e. 019-5028dca6d8bd8861270001b1.html ),
  3. # adds a class ( i.e. .page19 ) to the body and writes that back to the file.
  4.  
  5. require 'rubygems'
  6. require 'nokogiri'
  7. require 'open-uri'
  8.  
  9. module ClassMutator
  10. def add_css_class( *classes )
  11. existing = (self['class'] || "").split(/\s+/)
  12. self['class'] = existing.concat(classes).uniq.join(" ")
  13. end
  14. end
  15.  
  16. Dir.glob("../*.html") do |file|
  17.  
  18. @myfile = File.open(file, 'r');
  19. @baseName = File.basename(file)
  20.  
  21. # we want classes like .page123
  22. # - Strip down basename
  23. # - Remove leading zeros and add 'page'
  24. @pageNumber = "page" + ((@baseName[0..@baseName.index('-')-1]).to_i.to_s)
  25.  
  26. @page = Nokogiri::HTML(@myfile)
  27. @anchor = @page.css("body").first
  28.  
  29. if @page.at_css("body.#{@pageNumber}")
  30. # Page has class already
  31. # ~ Moving on
  32. else
  33. # Add class to existing classes
  34. @anchor.extend ClassMutator
  35. @anchor.add_css_class @pageNumber
  36. # Write it back to the file
  37. File.open(file, 'w') do |file|
  38. file.puts @page.to_html
  39. end
  40. end
  41.  
  42. end

Report this snippet  

You need to login to post a comment.