unwwwritten
Bend it to your will
Posted September 8th, 2007 at 5:08 am EDT by S. Brent Faulkner — View Comments
So, you've found an open source Ruby on Rails application that your think does something you need (say a weblog application). You install it on your server (or shared hosting environment) and you're generally quite happy with the way it works, but...
There's always a but isn't there?
I installed SimpleLog a little while ago, and for the most part it does it's job. It's simple, it looks how I want it to (with the help of the theme support) and, most importantly, it lets me publish my blog.
Now, as I was building a couple of themes for my blog I thought that SimpleLog should have a way to generate navigation links to any active pages in the blog.
Following the example of the methods defined in the Site helper class, I decided that a call similar to the following would be appropriate (in a view or layout):
<div id="nav"> <ul> <%= Site.nav_pages_linked @pages %> </ul> </div>
I'm not going to go into any of the basics of plugin creation and mix-ins to extend the functionality of a class using a plugin. The following code in vendor/plugins/simple_nav/lib/simple_nav.rb adds a couple of helper methods to the Site class. These helpers add the necessary helpers to generate the actual navigation links in the views or layouts.
class Site class << self def nav_page_linked(title, url, is_current = false) nav = %Q(<li#{' id="current"' if is_current}>) nav += %Q(<a href="#{url}">#{title}</a>) nav += %Q() end def nav_pages_linked(pages) nav = '' nav += nav_page_linked('Home', Site.full_url, is_home_page) pages.each do |p| url = Site.link_to_page(p.permalink) is_current = page_is('pages/'+p.permalink) nav += nav_page_linked(p.title, url, is_current) end unless pages.nil? nav end end end
Of course, this would require that every controller and action with a view or layout using it have loaded the appropriate instance variable with something like this:
@pages = Page.find(:all, :conditions => 'is_active = true')
To test the helpers, I simply added that line of code to the before_filter of the PostController and PageController classes as well as to the handle_unknown_request method of the ApplicationController.
In my next post, I'll explore how I was able to avoid modifying the controller classes to get the desired result.
Cheers.
--Brent
blog comments powered by Disqus