Daikini

We're human after all.

EventAttribute Rails Plugin: Boolean datetime attributes for AR models

Posted by Jonathan on June 21, 2007 at 06:05 AM

Jamis Buck posted a tip on using datetime columns in the database to represent boolean values. According to Jamis, this gives you the capability down the road to not only report whether the event occurred, but how frequently over various periods of time. I’ve been using this technique in many different project since I read his post and I must say that it has worked very well.

Jamis’ example was pretty simple and only provided read-only access to the attribute and no searching. I decided to kick this technique up a notch to provide read-write access as well as searching using dynamic finders. I’ve wrapped it all up in a Rails plugin that makes it easy to create boolean attributes from datetime columns.

To install the EventAttribute plugin you can:

./script/plugin install svn://svn.roundhaus.com/daikini/plugins/event_attribute

or if you prefer piston:

piston import svn://svn.roundhaus.com/daikini/plugins/event_attribute vendor/plugins/event_attribute

Here is an example of using the EventAttribute plugin to replicate Jamis’ example from his post:

   1  class Referral < ActiveRecord::Base
   2    event_attribute :applied_at, :attribute => 'pending', :nil_equals => true
   3    event_attribute :subscribed_on
   4  end
   1  referral = Referral.create(:applied_at => Time.now)
   2  referral.pending?           # => false
   3  referral.subscribed?        # => false
   4  
   5  referral.pending = true
   6  referral.applied_at         # => nil
   7  referral.pending?           # => true
   8  
   9  referral.subscribed = true
  10  referral.subscribed_at      # => Time.now
  11  referral.subscribed?        # => true
  12  
  13  
  14  # Dynamic finders are also added so that you can search on these boolean attributes.
  15  Referral.find_all_by_pending(true)  # => [Referral objects]
  16  
  17  # or
  18  Referral.find_by_name_and_pending_and_subscribed('John Smith', false, true)  # => Referral object
  19  
Tags: plugin, rails
Hierarchy: previous, next

Comments

There are 0 comments on this post. Post yours →

Post a comment

Required fields in bold.