Enter the EigenClass (singleton)
February 24th, 2007
Here’s another snip that is more about best practices, specifically inside the Model of a Rails application.
Often times you may be doing something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Ticket < ActiveRecord::Base def self.find_all_open find(:all, :conditions => [ "status = 'open'" ] ) end def self.assigned_to(name) find(:all, :conditions => ["assigned_to = '#{name}'"] ) end end Ticket.find_all_open Ticket.assigned_to("Ryan") |
There is nothing inheritantly wrong with the above, but there is a cleaner and more Ruby-ish way of doing it. You’ll often see this used in the Rails core code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Ticket < ActiveRecord::Base class << self def find_all_open Ticket.find(:all, :conditions => [ "status = 'open'" ] ) end def assigned_to(name) Ticket.find(:all, :conditions => ["assigned_to = '#{name}'"] ) end end end Ticket.find_all_open Ticket.assigned_to("Ryan") |
What we’ve done here is open up the Singleton class or EigenClass. An Eigenclass is a class that is specific to an object in which it is declared in. So, if you were to create an eigenclass on an instance of a Ticket, only that instance would have access to that class. So, in the above example only the Ticket class has those eigenclass methods, which will work just as our first example.
This example isn’t just Rails specific, you’ll find this used quite often in Ruby(no Rails framework) code. And, just to make a note for further learning, check out The Rails Way code refactoring example. It’s a great blog and I am a big fan of Jamis Buck’s work.


Sorry, comments are closed for this article.