diff options
Diffstat (limited to 'activesupport/lib/active_support')
-rw-r--r-- | activesupport/lib/active_support/core_ext/object/blank.rb | 22 |
1 files changed, 20 insertions, 2 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb index 9a1f663bf3..eb99bb1a36 100644 --- a/activesupport/lib/active_support/core_ext/object/blank.rb +++ b/activesupport/lib/active_support/core_ext/object/blank.rb @@ -2,11 +2,11 @@ class Object # An object is blank if it's false, empty, or a whitespace string. # For example, "", " ", +nil+, [], and {} are blank. # - # This simplifies + # This simplifies: # # if !address.nil? && !address.empty? # - # to + # ...to: # # if !address.blank? def blank? @@ -17,6 +17,24 @@ class Object def present? !blank? end + + # Returns object if it's #present? otherwise returns nil. + # object.presence is equivalent to object.present? ? object : nil. + # + # This is handy for any representation of objects where blank is the same + # as not present at all. For example, this simplifies a common check for + # HTTP POST/query parameters: + # + # 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' + def presence + self if present? + end end class NilClass #:nodoc: |