Doing stupid repetitive work for extended periods of time can cause serious drain bammage. Coming up with a static HTML page for WSF/PHP samples is just tedious work. If you’re like me, you use Emacs for everything you do including HTML editing. I was trying to create a page which listed all the samples. You could view the code as well as run it once you install WSF/PHP. The default was a standard directory listing by the web server. Trying to write a static HTML page with Emacs for that many samples is madness. Luckily with very few lines of Ruby, stupid repetitive work can be a source of fun.
A table listing a link to the script and showing the code would be nice. I could write a table in Emacs but filling it with content for all the samples is the problem.
<tr> <td> <a href="script_name.php">script name</a> <div> <code> code here </code> </div> </td> </tr>
Oh, I need to get a description up there as well. The README.SAMPLES file that’s in the samples folder has a description for each sample. Great, I could use that. Let’s throw some Javascript goodness with my favourite light weight JS framework mootools as well. It’s really easy to generate that for all the samples. Prettify was used to get the syntax highlighting. I did tried the syntaxhighlighter but after combining with moo the page got messy when the slide up happens. Anyways, FWIW, here’s the no brainer Ruby code.
#!/usr/bin/env ruby require 'cgi' lineno = 1 desc_row =<<E <tr class="%s"> <td class="desc">%s</td> </tr> E code_row =<<E <tr class="%s"> <td> <a href="%s">%s</a> (<a href="#" id="%s">show code</a>)<br /> <div id="%s"><br /> <pre class="prettyprint"> %s < /pre><br /> </div> </td> </tr> E js =<<E var %s = new Fx.Slide('%s'); %s.hide() $('%s').addEvent('click', function(e) { e = new Event(e); %s.toggle(); e.stop(); }); E File.open('README.SAMPLES', 'r').each do |line| if line =~ /^([a-z].*\.php)/ then (filename, description) = line.split(/[ \t]+-[ \t]+/) php_code = (File.open(filename.strip, 'r').readlines.collect do |l| CGI.escapeHTML(l) end).join.gsub(/\r/, '') row_state = ((lineno % 2) == 0) ? "even" : "odd" run_link = (filename.strip =~ /client/) ? "Run client" : "WSDL" class_toggle = "toggle-#{filename.strip.gsub(/.php/, '').gsub(/\//, '-').gsub(/_/, '-')}" class_code = "code-#{filename.strip.gsub(/.php/, '').gsub(/\//, '-').gsub(/_/, '-')}" js_var = "#{filename.strip.gsub(/.php/, '').gsub(/\//, '').gsub(/_/, '')}" if ARGV[0] == "-html" then printf(desc_row, row_state, description) printf(code_row, row_state, filename.strip, run_link, class_toggle, class_code, php_code) elsif ARGV[0] == "-js" then printf(js, js_var, class_code, js_var, class_toggle, js_var) end lineno += 1 end end
Had to do a bit of copying and pasting here and there and the page was done.
Posted in ruby, wsf/php · February 26th, 2008 · Comments (0)
No comments yet