What is the exact difference between Named Scopes(or Scopes in Rails 4), Lambdas and Procs?
Between Lambda and Proc, which one to choose?
What is the exact difference between Named Scopes(or Scopes in Rails 4), Lambdas and Procs?
Between Lambda and Proc, which one to choose?
1. Proc doesn't check the parameters passed, but lambda does
proc1 = Proc.new { |a, b| a + 5 }
proc1.call(2) # call with only one parameter
=> 7 # no error, unless the block uses the 2nd parameter
lambda1 = lambda { |a, b| a + 5 }
lambda1.call(2)
=> ArgumentError: wrong number of arguments (1 for 2)
Proc will throw error only if the block uses the second param.
proc2 = Proc.new { |a, b| a + b }
proc2.call(2) # call with only one parameter
=> TypeError: nil can't be coerced into Fixnum
2. Proc returns from the calling method, while lambda doesn't
def meth1
Proc.new { return 'return from proc' }.call
return 'return from method'
end
puts meth1
=> return from proc
def meth2
lambda { return 'return from lambda' }.call
return 'return from method'
end
puts meth2
=> return from method
If they are not called inside a method,
proc1 = Proc.new { return "Thank you" }
proc1.call
=> LocalJumpError: unexpected return
lambda1 = lambda { return "Thank you" }
lambda1.call
=> "Thank you"
3. Scopes/Named scopes are a feature of Rails
It is used to specify commonly used queries which can be referenced as method calls on the association objects or models
eg, in user.rb:
scope :developers, -> { where(:role => 'developer') }
You can use it as
@developers = User.developers
Scopes are chainable, so you can do queries like
@developers = User.developers.where(:age => 40)
The scope defined in the example, is exactly same as defining a class method, like below.
def self.developers
where(:role => 'developer')
end