Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Allow returning nil from a named_scope lambda

#1773

Returning an empty hash from a named_scope lambda basically means "do nothing."

I have found this to be a good pattern for disabling a named_scope under certain conditions, most commonly when the argument to the named_scope lambda was nil.

I propose returning nil should have the same effect as returning an empty hash. They both should mean "do nothing."


# with current implementation
named_scope :with_town_like, lambda { |term|
  if !term.blank?
    { :conditions => ['town LIKE ?', term] }
  else
    {}
  end
}


# new style, with nil as acceptable return value
named_scope :with_town_like, lambda { |term|
  { :conditions => ['town LIKE ?', term] } unless term.blank?
}

Reported by Elijah Miller · January 17th, 2009 @ 12:49 AM

State: resolved
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Daniel Morrison
    Daniel Morrison

    +1

    Looks good, and I've definitely wanted this pattern more than once.

    January 17th, 2009 @ 03:39 PM

  2. mileszs
    mileszs

    +1

    Straight-forward, makes a lot of sense, and I'd use it immediately.

    January 17th, 2009 @ 09:27 PM

  3. kris chambers
    kris chambers

    +1 Looks good. I have always been wanting this for a while.

    January 19th, 2009 @ 10:10 PM

  4. kris chambers
    kris chambers

    "I have been wanting this for a while." One day I will learn to read my comment before posting it.

    January 19th, 2009 @ 10:21 PM

  5. Repository
    Repository
    • State changed from new to resolved
    • Tag changed from patch to patch, verified

    (from [91b98cf0a5417ce4042a0b3cd1930d5a221b737f]) Returning nil from named scope lambda is equivalent to an empty hash [#1773 Allow returning nil from a named_scope lambda state:resolved]

    Signed-off-by: Pratik Naik pratiknaik@gmail.com http://github.com/rails/rails/co...

    March 12th, 2009 @ 03:14 PM