How To: Build a Wiki with Ruby on Rails – Part 2

Back in Part 1 of Building a Wiki with Ruby on Rails, we built the core wiki engine.

Time to add some syntax formatting.

These days, I’m pretty enamored of Haml, it’s more like HTML (unlike many other formatting engines) and it’s fast to write (unlike many other formatting engines).

1. Install Haml

Haml installs as a gem…1
gem install --no-ri haml
and a plugin…
haml --rails path/to/your/wiki

2. Create Your Haml View

Open up app/views/show.html.erb
and convert it to Haml. Replacing it to:

.content
%h1= @page.title.gsub('_', ' ')
= link_to('Edit', page_edit_path(:page_title => @page.title))
= link_to('History', page_history_path(:page_title => @page.title))
= "Last Updated #{time_ago_in_words(@page.revisions.last.created_on)} ago by #{Person.find(@page.revisions.last.person_id).name}"
%p= auto_link(@page.revisions.last.parsed_contents)

Now, your wiki should look exactly like it did before we plugged in Haml.

3. Add Haml Support for Revisions

Open up app/models/revision.rb and update def parsed_contents with:

def parsed_contents
contents = contents.gsub(/(w*_w*)/) {|match| "<a href='#{match.downcase}'>#{match.gsub('_', ' ')}</a>"}
h = Haml::Engine.new(contents)
h.to_html
end

4. Try It Out

Load up a page in your wiki, click ‘edit’, and add in some simple Haml, something like:

%strong this should be bold

5. Add in Some More (non-Haml) Formatting

Once you’re comfortable with Haml, maybe add in some other simple formatting rules into revision.rb

#Auto-renders any image URL
contents = self.contents.gsub(/s(.*.(jpg|gif|png))s/, '<img src="1"/>')

# Bolds text inside asterisks
contents = contents.gsub(/*(.*)*/, '<strong>1</strong>')

# Wraps <code> around text inside '@'
contents = contents.gsub(/@(.*)@/, '<code>1</code>')

# Blockquotes text inside double-quotes
contents = contents.gsub(/s"(.*)"s/, '<blockquote>"1"</blockquote>')

# Italicizes text inside underscores
contents = contents.gsub(/s_(.*)_s/, '<em>1</em>')

6. Make it Better

After playing around with Haml and other formatting, you’ll quickly see some quirks – some room for improvement. Go for it, and let me know when you get something interesting.

1. Remember to vendor your gems.

You should get my email