I’m reading Beginning Rails 3. The book creates a project where Users can post Articles. Now inside the Article object they create 3 scopes like so:
scope :published, where("articles.published_at IS NOT NULL")
scope :draft, where("articles.published_at IS NULL")
scope :recent, lambda { published.where("articles.published_at > ?", 1.week.ago.to_date)}
Now the last lambda function I can replace it with this scope statement and I get the same results:
scope :recent, where("published_at > ?", 1.week.ago.to_date)
What is the advantage of using a lambda here?
If you do not use
lambdathe time1.week.agowill be calculated at application startup and cached. So even if it has been months your application has been running, it will still point to time 1 week before application start.You do not notice this in development environment, because application code gets reloaded on each request. Using lambda, you ensure that it is calculated fresh for each call to your scope, even in production environment.