From: Ezra Zygmuntowicz Date: 2006-10-19T10:33:12+09:00 Subject: Re: whats this lambda code doing? On Oct 18, 2006, at 6:15 PM, Ken Bloom wrote: > On Thu, 19 Oct 2006 10:02:11 +0900, David Vallner wrote: > >> Ezra Zygmuntowicz wrote: >>> klasses.inject(block) do |blk, klass| >>> lambda { klass.with_scope(scope_hash, &blk) } >>> end.call >>> >>> That outer block that ends on end returns the lambda made inside >>> of that >>> block. So end.call ends up being lambda { klass.with_scope >>> (scope_hash, >>> &blk) }.call >>> >> >> Hmm. Unless I'm very mistaken, it would also only call the lambda for >> the last object in klasses, generating several garbage (and >> relatively >> expensive) lambdas. Boggle. Am I missing something? >> >> David Vallner > > This some wierd kind of lambda chaining. You're confusing "block" with > "blk", so you're thinking that each version of this code is using the > original block, but this is not so. Each lambda is chained to call the > previous lambda. I haven't got a clue what with_scope does, but > this would > all be a lot easier to understand if it was possible to eliminate the > lambda, and deal with each class separately. > > -- > Ken Bloom. PhD candidate. Linguistic Cognition Laboratory. with_scope is an ActiveRecord thing for scoping your where clauses. It works like this: Post.with_scope(:find => {:conditions => ["customer_id = ?", @customer.id]}) do @post = Post.find(:all) end And you can nest these with_scope blocks inside each other so the innermost #find method gets the scoped :conditions merged with its own conditions. So the original posters code is taking a list of Model classes and scoping the find and create calls on them to a specific blog.id . But I have to agree that code is too clever for its own good. Twisting it up like that may make a golfer happy, the next guy to come across it will be confused when it could have been stated clearer. Cheers. -- Ezra Zygmuntowicz -- Lead Rails Evangelist -- ez@engineyard.com -- Engine Yard, Serious Rails Hosting -- (866) 518-YARD (9273)