Ruby
The last preparation step is to show Ruby code with highlighted syntax using Ruby itself. For this we will need to install a
syntax gem.
Run on your host:
gem install syntax
Then create a simple Ruby script:
require 'rubygems'
require 'syntax/convertors/html'
convertor = Syntax::Convertors::HTML.for_syntax "ruby"
puts convertor.convert( File.read(ARGV[0]) )
Running this from PHP is very similar to how we captured script results, the only difference is that we do not need to strip HTML symbols:
function show_code($script='')
$output='<div class="source"><span class="ruby">';
$script_root='~/cgi-bin';
$gem_home='~/bin/ruby';
$ruby_path=~/bin/ruby/bin';
$colorer='~/cgi-bin/ruby_colorer.rb';
$cmd="GEM_HOME=$gem_home PATH=$ruby_path:\$PATH ruby $colorer $script_root/$script 2>&1";
exec($cmd,$result);
$output.=implode($result,"\n");
$output.='</pre></div>';
print $output;
}
We also have to add ruby styles to our CSS:
/* Syntax highlighting */
.ruby .normal {}
.ruby .comment { color: #005; font-style: italic; }
.ruby .keyword { color: #A00; font-weight: bold; }
.ruby .method { color: #077; }
.ruby .class { color: #074; }
.ruby .module { color: #050; }
.ruby .punct { color: #447; font-weight: bold; }
.ruby .symbol { color: #099; }
.ruby .string { color: #944; background: #FFE; }
.ruby .char { color: #F07; }
.ruby .ident { color: #004; }
.ruby .constant { color: #07F; }
.ruby .regex { color: #B66; background: #FEF; }
.ruby .number { color: #F99; }
.ruby .attribute { color: #7BB; }
.ruby .global { color: #7FB; }
.ruby .expr { color: #227; }
.ruby .escape { color: #277; }
.source {
background: #fff;
width: 95%;
border: 2px inset #999;
padding: 10px;
font-size: 1.6em;
overflow: auto;
margin: 4px 0px;
width: 95%;
}
The content of ruby_colorer.rb above is a result of <?php show_code('ruby_colorer.rb') ?>
The final touch for this is to implement caching for results to avoid running this script each time the page is loaded.