/ Published in: Ruby
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
Expand |
Embed | Plain Text
# This ruby script loads all .html files in the folder above, check for a class # on the body, generate a class from the filename ( i.e. 019-5028dca6d8bd8861270001b1.html ), # adds a class ( i.e. .page19 ) to the body and writes that back to the file. require 'rubygems' require 'nokogiri' require 'open-uri' module ClassMutator def add_css_class( *classes ) existing = (self['class'] || "").split(/\s+/) self['class'] = existing.concat(classes).uniq.join(" ") end end Dir.glob("../*.html") do |file| @myfile = File.open(file, 'r'); @baseName = File.basename(file) # we want classes like .page123 # - Strip down basename # - Remove leading zeros and add 'page' @pageNumber = "page" + ((@baseName[0..@baseName.index('-')-1]).to_i.to_s) @page = Nokogiri::HTML(@myfile) @anchor = @page.css("body").first if @page.at_css("body.#{@pageNumber}") # Page has class already # ~ Moving on else # Add class to existing classes @anchor.extend ClassMutator @anchor.add_css_class @pageNumber # Write it back to the file File.open(file, 'w') do |file| file.puts @page.to_html end end end
You need to login to post a comment.
