Background here.
In the above link, the following example is given:
class << self
def by_author(author)
where(:author_id => author.id)
end
Class methods in Ruby are really just members of the singleton class, and doing class << self
involves opening the singleton class directly and adding to it, removing the need to declare it in each method definition.
This article on Ruby singletons does a good job explaining.
As far as class methods being chainable, that isn't something specific to class methods, the second method call is simply called on the object returned from the first. For example:
bar = foo.do_something.do_more
is equivalent to:
tmp = foo.do_something
bar = tmp.do_more
In Rails, this chainability is most often used for building SQL queries (e.g., with where
or order
, etc.). This is achieved because each of these methods returns an ActiveRecord Relation.
The reason
foo.scoped.my_foo_class_method
works is because of ActiveRecord::Relation#method_missing doing the following:
elsif @klass.respond_to?(method)
scoping { @klass.send(method, *args, &block) }
Which checks if the ActiveRecord class responds to the method called, and if so, calls that.