When to use a lambda in Ruby on Rails?

Viewed 56097

When should a lambda or proc be used? I have seen them described as anonymous functions, but I am struggling to understand this concept. I would appreciate any links to or examples of when you might use one in Ruby, but especially in Ruby on Rails.

7 Answers

It is a piece of code that allows you to pass around.

It is especially useful in named_scope, it allows to you do something like this:

named_scope :scoped_by_user, lambda {|user| {:conditions=>{:user_id=>user.id}}}

Say you have a Project model and you want to get all the projects for one particular user, you can do something like this:

Project.scoped_by_user(123)

Where I've seen Lambda used is in testing...

lambda do
    post :create, :user => @attr
end.should_not change(User, :count)

Lambda allows you to have that test at the end to make sure that the code executed in the lambda block doesn't change change the User count.

lambda is exceptionally useful in named_scope, so that you can pass parameters to named_scopes.

Many validator options accept a lambda or Proc if the work is too simple to warrant a named function. For example, :if and :unless.

validates :thing, presence: true, unless: ->(obj) { obj.something? }

:message will accept a Proc for custom validator messages.

validates :terms, acceptance: {
    message: ->(person) "%{person.name} must accept our terms!"
}

Generally, lambdas (and callbacks in general) are useful as a lightweight way to allow more customization than a string or number allows, but without the user having to write a full class.

Related