18.12.2012 Views

Rails Magazine - Issue 3

Rails Magazine - Issue 3

Rails Magazine - Issue 3

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

6<br />

Create a simple code snippet app with <strong>Rails</strong> by Michelangelo Altamore<br />

6<br />

Time to move on the next one.<br />

Task 2: Snippet Highlighting<br />

For this task we will use the library CodeRay by Kornelius<br />

Kalnbach. Check if it is already installed on your system with<br />

gem list coderay. If it is not listed you can install by running:<br />

$ sudo gem install coderay.<br />

Our aim is to let Snippety being able to use the coderay<br />

gem to render an highlighted version of a snippet body according<br />

to its language syntax.<br />

So we configure that dependency in config/environment.rb by<br />

adding the line:<br />

config.gem "coderay"<br />

We still don’t know how to interact with that library. However<br />

that knowledge is not that far away, by running ri CodeRay<br />

you can see its usage; I report here what is relevant for us:<br />

Highlight Ruby code in a string as html<br />

require ‘coderay’<br />

print CodeRay.scan(‘puts “Hello, world!”’, :ruby).html<br />

# prints something like this:<br />

puts &quot;Hello, world!&quot;<br />

Highlight C code from a file in a html div<br />

require ‘coderay’<br />

print CodeRay.scan(File.read(‘ruby.h’), :c).div<br />

print CodeRay.scan_file(‘ruby.h’).html.div<br />

You can include this div in your page. The used CSS<br />

styles can be<br />

printed with<br />

% coderay_stylesheet<br />

...<br />

A bridge too red<br />

The documentation tells us that:<br />

1. we can obtain coderay’s stylesheet with the command<br />

coderay_stylesheet<br />

2. we can highlight a string calling scan method on the<br />

CodeRay class<br />

In order to integrate coderay stylesheet we run the following<br />

inside root folder of Snippety:<br />

$ coderay_stylesheet > public/stylesheets/coderay.css<br />

You should obtain the stylesheet file. To get it loaded we<br />

must modify application layout, as you can see on line 6 in<br />

app/views/layouts/application.html.erb file:<br />

...<br />

4 <br />

5 <br />

6 <br />

7 <br />

8 <br />

...<br />

The stylesheet should be loaded now (you can look at the<br />

source to be sure).<br />

Now it’s time to explore CodeRay from the <strong>Rails</strong> console:<br />

$ script/console<br />

Loading development environment (<strong>Rails</strong> 2.2.2)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!