Class: Object
- Inherits:
- BasicObject
- Defined in:
- lib/rss_feed/object.rb
Overview
Monkey-patching the Object class to add convenience methods for checking presence or absence of content.
Instance Method Summary collapse
-
#blank? ⇒ true, false
An object is blank if it’s false, empty, or a whitespace string.
-
#presence ⇒ Object
Returns the receiver if it’s present otherwise returns
nil. -
#present? ⇒ true, false
An object is present if it’s not blank.
Instance Method Details
#blank? ⇒ true, false
An object is blank if it’s false, empty, or a whitespace string. For example, nil, ”, ‘ ’, [], {}, and false are all blank.
This simplifies
!address || address.empty?
to
address.blank?
22 23 24 25 26 |
# File 'lib/rss_feed/object.rb', line 22 def blank? # If the object responds to `empty?`, checks if it's empty or equals 'NaN'. # Otherwise, checks if the object is nil. respond_to?(:empty?) ? (empty? || self == 'NaN') : !self end |
#presence ⇒ Object
Returns the receiver if it’s present otherwise returns nil. object.presence is equivalent to
object.present? ? object : nil
For example, something like
state = params[:state] if params[:state].present?
country = params[:country] if params[:country].present?
region = state || country || 'US'
becomes
region = params[:state].presence || params[:country].presence || 'US'
44 45 46 |
# File 'lib/rss_feed/object.rb', line 44 def presence self if present? end |
#present? ⇒ true, false
An object is present if it’s not blank.
6 7 8 |
# File 'lib/rss_feed/object.rb', line 6 def present? !blank? end |