Not logged in (Log in or Sign up)

unwwwritten

Bend it to your will - Episode II

Last time, we looked at a helper that I wanted to add to the SimpleLog Site class. In order to use it in that form, I would have to modify all the appropriate controller classes individually. They would each have to perform a Page.find before rendering the view or layout which would make the call to out nifty little navigation link generator.

However, my goal here is that I can update SimpleLog at any time without worrying about what changes I've made to the source. So, plugins or patches would be a preferred way of hooking it up. In addition, if someone else wanted the functionality that I'm implementing, plugins would be easier to distribute and/or support than patches.

So, the question then became "How do I implement this as a plugin?"

The Life of a Plugin

In my last post, I said I wasn't going to go into the basic of plugins. A bit is necessary though, to really get the evolution of what I'm doing here. Within our plugin (and most others) the basic flow is pretty straight forward.

First, init.rb loads the plugin:

require 'simple_nav'

Then, the plugin code (in our case, lib/simple_nav.rb) defines a module to be included into the appropriate class(es). That module defines a function to load the page array and installs it as a before_filter for the controller class that includes it:

module SimpleNav #:nodoc:
  def self.included(base)
    base.class_eval do
      # Load active pages into array
      def preload_pages
        @pages = Page.find_all_by_is_active(true)
      end
      # Use before filter to load page array
      before_filter :preload_pages
    end
  end
end

Hooking it up

Now, the only modification required to use this version of our plugin in SimpleLog is to include the SimpleNav module into the ApplicationController. We still need to modify SimpleLog, but it is literally one line of code that needs to be added.

Call me a perfectionist, but this is still not quite what I'd envisioned. My next post will show you how I managed to take this one step further and eliminated that "one line of code".

Cheers.

--Brent

blog comments powered by Disqus