Wednesday, May 21, 2008

Posting Ruby

So, I broke down and did some research on how to post code to blogger so that it doesn't look hideous. It wasn't nearly as simple as I wanted it to be (most notably, it was a serious pain to use cocoa to use the pasteboard for converting text)... so I hacked together a little rails project that handles things for me using web forms. It would be a long post to explain all the details, but I'll cover the basics.

First, sudo gem install syntax. Then create a new rails project and get it up and running. When you've got that, generate a controller called "Convert". The code for the controller should look like this:
class ConvertController < ApplicationController
def ruby
render :action => :ruby
end
def to_html
require 'syntax/convertors/html'
convertor = Syntax::Convertors::HTML.for_syntax params[:type]
@code = convertor.convert(params[:text]).gsub(/<span class="punct">([^<]*)<([^<]*)</, "<span class=\"punct\">\\1&lt\\2<")
render :action => :to_html
end
end

And then you'll need a view for 'ruby.html.erb'.:
<h1>Convert What?</h1>
<p>
<% form_tag('/convert/to_html') do %>
<table><tr><td><%= text_area_tag 'text', '', {:cols => 80, :rows => 30} %></td>
<td><%= radio_button_tag 'type', 'ruby', true%>Ruby<br/>
<%= radio_button_tag 'type', 'xml'%>HTML/XML<br/>
<%= submit_tag 'convert to HTML' ><td>tr><table>
<% end %>
</p>

...And a basic response form in 'to_html.html.erb':
<h1>The raw HTML:</h1>
<pre><%= text_area_tag('whatever', @code, {:cols => 80, :rows => 30}) %></pre>
<h1>The results:</h1>
<%= @code.gsub(/&amp;/, '&') %>

...You'll also want to set up the CSS for your site, using the CSS from the site where I stole this idea from. Polishing things is an exercise left to the reader... but that should get you started.

No comments: