By now we have a working WIKI on Ruby on Rails, however it lacks some features which bring the WIKI fully to life. Namely, the ability to link WIKI posts together. We will clone the syntax from some of the popular WIKI's. Links to other WIKI pages will be wrapped in double brackets, [[LikeThis]].
Ruby has a powerful syntax for dealing with regular expressions. If you haven't worked with regular expressions before, this may feel overwhelming. In a nutshell, a regular expression is a pattern matching language for searching strings. We will add a new method to the Revision model. Edit app/models/revision.rb and add the following method:
# Regular Expression to match words surrounded
# by double brackets [[LikeThis]]
WIKI_LINK = %r/\[\[\s*([^\]\s][^\]]+?)\s*\]\]/
# Return the Revision's content marked up in HTML format
def to_html
rawtext = content
if rawtext.nil?
return ""
end
# First, HTMLify the wiki links
rawtext.gsub!( WIKI_LINK ) do |matched_text|
name = matched_text.gsub(/[\[\]]/,"")
"<a href=\"" + name + "\">" + name + "</a>"
end
rawtext
end
Ruby's gsub method can find patterns matching a regular expression, and allow a block of code (within the do block) to be executed on it. The string returned from the do block replaces the searched text. Therefore this is a basic search & replace method.
In our code, when any grouping of [[WikiLink]] is found, the brackets are stripped off, and the link replaced with an HTML anchor (<a href>) tag.
Now we must modify the HTML in our VIEW to call our new method. Modify the last line in app/views/wiki/view.rthml to appear as so:
<%= @page.revisions.last.to_html if @page %>
Now, rather than simply displaying the revision contents, they are transformed via the to_html method we just created.
Extra Credit
I won't cover them in this tutorial, but there are a variety of extra credit activities that could be performed to make this program more functional.
- Markup - Utilize a markup/markdown library to provide full support for text manipulating (such as bold, italic, headers, etc). A nice one to use is called RedCloth. You can add support to this library in the newly created to_html method on the Revision model.
- Revision History - Since previous versions of the content are stored within the database, the controller can be modified to display content for previous versions. I'd recommend adding a new button on the layout to view the history.
- Tagging - Tagging WIKI pages would require the addition of new columns to the database schema. There are also Ruby gems available to assist in adding tagging support.
- HTML Prettiness - The HTML in this tutorial is rather bland. Modification to the layout and views can do wonders for making this appear like a fully functional application. For inspiration, look at this layout gala informing you how to utilize CSS to layout a page.


0 comments:
Post a Comment