I’m looking at the source code of a model Article.rb.
It has bunch of instance methods and then this.
class << self
def search(query, groups, order = nil)
groups = [groups].flatten
find(:all, :select => “articles.*”, :joins => “INNER JOIN linkings
ON
articles.id = linkings.linkable_id”, :conditions => [“linkings.group_id
IN
(#{groups.join(‘,’)}) AND (linkings.linkable_type=‘Article’) AND (
articles.title LIKE ? OR articles.body LIKE ? OR (SELECT tags.name FROM
tags
INNER JOIN taggings ON tags.id = taggings.tag_id WHERE
taggings.taggable_id=
articles.id AND taggings.taggable_type = ‘Article’ AND tags.name LIKE ?)
IS
NOT NULL)”, “%#{query}%”, “%#{query}%”, “%#{query}%”], :group => "
articles.id", :order => order)
end
end
My question is why go all the way and do class << stuff to get a class
method. What’s wrong with using just
def self. search(query, groups, order = nil)
…
end
What are the design benefits. I have read ruby book and can understand
in
some cases it’s useful. But in this case when we have a simple model why
not
just have self.method_name.
What are the design benefits. I have read ruby book and can understand in
some cases it’s useful. But in this case when we have a simple model why not
just have self.method_name.
(an essay from last year that just got resuscitated today amidst some
singleton-class discussion on IRC)
Mind you, Neeraj was mainly asking about the relative merits of the
two techniques, rather than the underlying stuff. To which I would
say: the class << obj technique is probably chosen mostly because it
sort of “normalizes” the appearance of the code, so that every method
definition is based on a bareword. On the other hand, the other way
gives you an explicit visual reminder, with each method, that the
method is being added to an object on a singleton basis.