Format Ruby code in HTML
#!/usr/bin/ruby #file: ruby2html.rb require 'rubygems' require 'syntax/convertors/html' require 'projxslt' # <- this is my own class to do an XSLT transform require 'rexml/document' include REXML class Ruby2Html def initialize(rubyfile, htmlfile) code = File.read(rubyfile) convertor = Syntax::Convertors::HTML.for_syntax "ruby" code_html = convertor.convert(code) tempfile = '../temp/ruby2html.xml' xslfile = '../ruby2html/ruby2html.xsl' save_file(tempfile, code_html) px = Projxslt.new(tempfile, xslfile) buffer = px.transform() save_file(htmlfile, buffer) end def save_file(filename, buffer) file = File.new(filename, 'w') file.puts buffer file.close end end if __FILE__ == $0 r2h = Ruby2Html.new('ruby2html.rb', '../temp/ruby2html.html') puts 'completed' end
file: ruby2html.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" version="1.0"> <xsl:output method="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" encoding="ISO-8859-1"/> <xsl:template match="/"> <xsl:element name="html"> <head> <title>Sample code</title> <link rel="stylesheet" type="text/css" href="ruby2html.css" /> </head> <body> <div id="wrap"> <xsl:apply-templates /> </div> </body> </xsl:element> </xsl:template> <xsl:template match="pre"> <xsl:copy-of select="."/> </xsl:template> </xsl:stylesheet>
Here's the output from the formatted Ruby HTML code [twitxr.com]
Referemce: Syntax Manual [rubyforge.org]