Skip to content
A tiny convenience for guarding against emptiness (in your code, not in your life)
Ruby
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
spec
LICENSE
README.mkdn
emptor.rb

README.mkdn

Emptor

A convenient conditional that excludes empty objects (Enumerables, in general).

EMPTOR CAVEAT

Emptor is a hack. It's merely a shorter expression for those who want to consider empty collections to be falsy. Calling

$ this._or_ that

Returns the first object that's either a non-empty collection (collections are assumed if the operand responds_to :empty?) or a non-collection that's truthy (in the Colbertian sense). So:

$ []._or_ [1,2,3]
# => [1,2,3]

$ "yep"._or_ [1,2,3]
# => "yep"

$ []._or_ []
# => nil

One example of usage would be while performing an ActiveRecord find with scoping, where you'd like to return an unscoped set if the first set turns out empty.

This:

$ User.all.with_photos.present? ? User.all.with_photos : User.all

Becomes:

$ Person.all.with_photos._or_ Person.all

That's all, folks.

Something went wrong with that request. Please try again.