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.

Object#nonblank? (analogous to Ruby's Numeric#nonzero?)

#3620

About a year ago we built on Rails' blank? method with a nonblank? method that is analogous to Ruby's Numeric#nonzero? method: it either returns the object itself (if not blank) or nil (if blank). This makes it easy to treat blank parameters the same as missing ones, and allows chaining.

For example, this:

state = params[:state] unless params[:state].blank? country = params[:country] unless params[:country].blank? region = state || country || 'US'

becomes:

region = params[:state].nonblank? || params[:country].nonblank? || 'US'

This has been working well for us and hopefully others will find it useful to too.

The attached patch has full documentation and tests.

Reported by Colin Kelley · December 27th, 2009 @ 12:29 AM

State: committed
Milestone: none
Assigned to: nobody
Importance: none

Activity

  1. Colin Kelley
    Colin Kelley

    [oops, reformatting]

    For example, this:

    state   = params[:state]   unless params[:state].blank?
    country = params[:country] unless params[:country].blank?
    region  = state || country || 'US'
    

    becomes:

    region = params[:state].nonblank? || params[:country].nonblank? || 'US'
    

    December 27th, 2009 @ 12:34 AM

  2. Prem Sichanugrist (sikachu)
    Prem Sichanugrist (sikachu)

    I have some suggestion. Since we already have present? method which would do almost the same thing. Should we modify present? method return object itself if it's not blank? instead?

    region = params[:state].present? || params[:country].present? || 'US'
    

    December 27th, 2009 @ 04:36 PM

  3. DHH
    DHH
    • State changed from new to committed

    Committed as Object#presence.

    December 28th, 2009 @ 01:55 AM