From ee9382e597d38c266cfac5899a7a5c7d3fab94f4 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 7 Jun 2009 01:19:12 +0200 Subject: AS guide: explains blank? and present? --- .../guides/source/active_support_overview.textile | 36 ++++++++++++++++++++++ 1 file changed, 36 insertions(+) (limited to 'railties/guides/source') diff --git a/railties/guides/source/active_support_overview.textile b/railties/guides/source/active_support_overview.textile index 22539112e0..3cf4c3b844 100644 --- a/railties/guides/source/active_support_overview.textile +++ b/railties/guides/source/active_support_overview.textile @@ -13,7 +13,43 @@ h3. Extensions to All Objects h4. +blank?+ and +present?+ +The following values are considered to be blank in a Rails application: +* +nil+ and +false+, + +* strings composed only of whitespace, i.e. matching +/\A\s*\z/+, + +* empty arrays and hashes, and + +* any other object that responds to +empty?+ and it is empty. + +WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank. + +For example, this method from +ActionDispatch::Response+ uses +blank?+ to easily be robust to +nil+ and whitespace strings in one shot: + + +def charset + charset = String(headers["Content-Type"] || headers["type"]).split(";")[1] + charset.blank? ? nil : charset.strip.split("=")[1] +end + + +That's a typical use case for +blank?+. + +Here, the method +instantiate_observers+ of Active Record has nothing to do if there are no observers: + + +def instantiate_observers + return if @observers.blank? + # ... +end + + +The method +present?+ is equivalent to +!blank?+: + + +assert @response.body.present? # same as !@response.body.blank? + h3. Extensions to +Module+ -- cgit v1.2.3