Named scopes, still needed ?
Wijnand Wiersma vr 25 jun 10
I am wondering what the use cases are for named scope in the Rails3 release.
Just creating a class method which returns an ActiveRelation object gives more clear code and allows for more customisations.
The most obvious use case are old rails 2.3 lambda scopes.
See this example:
named_scope :for, lambda {|author| {:conditions => ["customer_id IS NULL OR customer_id = ?", author.customer_id]} }
You can call this like
Post.for(author) # eg anything that responds to customer
This looks like a method call, so I was happy to be able to do this in Rails3:
def self.for(testmaker) where(:customer_id => testmaker.customer_id) end
Now it’s not just like calling a method, it actually is a method!
For me this feels far more natural and thanks to Arel magic it just works in the same way too.
You can still chain it as if it was an instance method:
Post.limit(10).for(author)
So if we had to use the hackish lambda scopes regularly (the real need is questionable off course) and now we are better served with a class method: wouldn’t it be far more natural to skip named scopes and just create intelligent class methods?
Rails2:
named_scope :published, :conditions => {:published => true}
Rails3:
scope :published, where(:published => true)
The Rails3 way I like it:
def self.published where(:published => true) end
So unless anybody can give me a compelling reason to use named scopes (lines of code arguments will be rejected) I will proceed on this path.
I think Rails apps should become more Ruby like instead, too much magic hurts my brains.
And remember, everytime you write a lambda scope, god kills an unicorn.
Gepost in hor | 2 reacties
Welkom op Holland On Rails
Het startpunt voor Ruby On Rails in Nederland. Vind de laatste technieken, meningen en nieuwtjes.Recente Jobs
Gezocht: Ruby On Rails ontwikkelaar (junior of senior)
Eet, drink en droom jij over Ruby On Rails? Wil jij het liefste dag en nacht bezig zijn met jehobby; super coole webapplicaties ontwikkelen in Ruby On Rails?
Dan willen wij jou graag een podium bieden om je Ruby skills te vertonen aan onze nationale en internationale klanten!
@ Internetbureau Holder, Obdam
Bekijk alle jobs »»
Gereedschapskist
Onmisbare tools vooriedere developer!
- Ruby On Rails
Framework voor de web 2.0 developer. Eindelijk vooruitgang! - TextMate
Editor for true pro's
Typ, tab, top :-)
Nee, niet voor Win. - Made On A Mac
En nou is het over met die saaie grijze Windows bak van je!
Auteurs op deze site
Chris Obdam
'Less is more' evangelist, past dit ook dagelijks toe op zijn tandenborstel.Chiel Wester
Snelheidswonder op Ruby wielen. Leuk om mee te pair-programmen ;-)
Roy van der Meij vr 25 jun 10 11:12
For scopes with parameters I totally agree, those should be put in a class method.
But for your last example I prefer the “scoped” way.
Marten Veldthuis vr 25 jun 10 10:17
+1
Plaats je reactie