Developer Tips 2

Posted by Jim Gay on Tuesday, February 24, 2009 | |

Working on building that great extension to track widgets, doodads and thingamajigs? You’ll probably need a way to keep track of who created and updated what.

Radiant takes care of tracking the creator and updater of pages, snippets, layouts and even users with the UserActionObserver so perhaps there’s a way to use that in your own quest to track whatchamacallits.

The UserActionObserver is loaded in your config/environment.rb with config.active_record.observers = :user_action_observer

You could create your own observer and add that to your environment with config.active_record.observers = :user_action_observer, :gizmo_observer. The UserActionObserver looks like this:

class UserActionObserver < ActiveRecord::Observer
  observe User, Page, Layout, Snippet
  cattr_accessor :current_user
  def before_create(model)
    model.created_by = @@current_user
  def before_update(model)
    model.updated_by = @@current_user

You could go right ahead and make that GizmoObserver that you need, but if you only need to perform the same function as the UserActionObserver why not make your life easier and use what’s already there.

Here’s how Radiant set’s up the relationships in the observed models:

  belongs_to :created_by, :class_name => 'User'
  belongs_to :updated_by, :class_name => 'User'

That’s simple enough to repeat in your extension. Just add created_by_id and updated_by_id fields to your appropriate table and setup the same relationships.

Once you’ve done that, the last step is simple: just update your whatever_extension.rb

  def activate
    UserActionObserver.instance.send :add_observer!, DooHickey

There are other extensions out there that already do this, so if you need to see it in action, check out their code.