Format Ruby code in HTML
1 2 #!/usr/bin/ruby 3 4 #file: ruby2html.rb 5 6 require 'rubygems' 7 require 'syntax/convertors/html' 8 require 'projxslt' # <- this is my own class to do an XSLT transform 9 require 'rexml/document' 10 include REXML 11 12 class Ruby2Html 13 def initialize(rubyfile, htmlfile) 14 code = File.read(rubyfile) 15 convertor = Syntax::Convertors::HTML.for_syntax "ruby" 16 code_html = convertor.convert(code) 17 18 tempfile = '../temp/ruby2html.xml' 19 xslfile = '../ruby2html/ruby2html.xsl' 20 save_file(tempfile, code_html) 21 22 px = Projxslt.new(tempfile, xslfile) 23 buffer = px.transform() 24 save_file(htmlfile, buffer) 25 26 end 27 28 def save_file(filename, buffer) 29 file = File.new(filename, 'w') 30 file.puts buffer 31 file.close 32 end 33 end 34 35 if __FILE__ == $0 36 r2h = Ruby2Html.new('ruby2html.rb', '../temp/ruby2html.html') 37 puts 'completed' 38 end
file: ruby2html.xsl
1 2 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 3 xmlns="http://www.w3.org/1999/xhtml" 4 version="1.0"> 5 6 <xsl:output method="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" 7 doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" 8 encoding="ISO-8859-1"/> 9 10 <xsl:template match="/"> 11 <xsl:element name="html"> 12 13 <head> 14 <title>Sample code</title> 15 <link rel="stylesheet" type="text/css" href="ruby2html.css" /> 16 </head> 17 18 <body> 19 <div id="wrap"> 20 <xsl:apply-templates /> 21 </div> 22 </body> 23 24 </xsl:element> 25 </xsl:template> 26 27 <xsl:template match="pre"> 28 <xsl:copy-of select="."/> 29 </xsl:template> 30 31 </xsl:stylesheet>
Here's the output from the formatted Ruby HTML code [twitxr.com]
Referemce: Syntax Manual [rubyforge.org]