I was reading about creating a Fluent Interface for ruby delegation by Bryan Helmkamp and I realized it would be neat if ActiveRecord implemented a fluent interface.
For an overview of fluent interfaces read Martin Fowler’s explanation
Check this out:
Find:
Person.find(:all).with(:name => 'Eric', :active => 1).limit(20).order_by(:created_at).include(:address, :friends)
Find with scope
Person.find(:all).scoped_by(:active).with(:name => 'Eric')
“Dynamic” Finders
Person.find(:first).by(:first_name, :last_name).with('Eric', 'Allam')
FInd or Initialize by
Person.find(:or).initialize.by(:first_name => 'Eric')
Validations
class Person < ActiveRecord::Base
validates(:presence).of(:first_name, :last_name).say("cannot be empty dummy")
validates(:uniqueness).of(:url).if(:url?)
end
Associations
class Person < ActiveRecord::Base
has_one(:mom).of_class(Person).with_key(:mother_id)
end
Personally I like the Fluent Interface for ActiveRecord. It reads even better than before. I am not sure how hard it would be to implement, because I have never written a Fluent Interface, but I’d imagine it wouldn’t be easy. I might just have to give it a whirl.
Sorry, comments are closed for this article.