Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: named_scope, lambda and blocks

I thought the following two were equivalent:

named_scope :admin, lambda { |company_id| {:conditions => ['company_id = ?', company_id]} }  named_scope :admin, lambda do |company_id|    {:conditions => ['company_id = ?', company_id]} end 

but Ruby is complaining:

ArgumentError: tried to create Proc object without a block 

Any ideas?

like image 682
Gav Avatar asked Sep 25 '09 11:09

Gav


People also ask

What are procs in Rails?

A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.

How is a block different from a proc?

Procs are objects, blocks are notA proc (notice the lowercase p) is an instance of the Proc class. This lets us call methods on it and assign it to variables. Procs can also return themselves. In contrast, a block is just part of the syntax of a method call.

What is the difference between block proc and lambda in Ruby?

When using parameters prefixed with ampersands, passing a block to a method results in a proc in the method's context. Procs behave like blocks, but they can be stored in a variable. Lambdas are procs that behave like methods, meaning they enforce arity and return as methods instead of in their parent scope.

What is the main difference between procs and lambdas?

There are only two main differences. First, a lambda checks the number of arguments passed to it, while a proc does not. This means that a lambda will throw an error if you pass it the wrong number of arguments, whereas a proc will ignore unexpected arguments and assign nil to any that are missing.


1 Answers

it's a parser problem. try this

named_scope :admin, (lambda do |company_id|    {:conditions => ['company_id = ?', company_id]} end) 
like image 67
Martin DeMello Avatar answered Oct 05 '22 17:10

Martin DeMello