刘华佼的全栈学习记录

5-11 blank?是什么东东

| Comments

在dash上搜索blank

出现了文档rails/activesupport/lib/active_support/core_ext/object/blank.rb

往上翻阅:

class Object
  # An object is blank if it's false, empty, or a whitespace string.
  # For example, +false+, '', '   ', +nil+, [], and {} are all blank.
  #
  # This simplifies
  #
  #   !address || address.empty?
  #
  # to
  #
  #   address.blank?
  #
  # @return [true, false]
  def blank?
    respond_to?(:empty?) ? !!empty? : !self
  end

翻译一下:一个对象如果是false,空的,或者一个空白字符(串),例如:false, '', ' ', 或者nil,[], {}, 都是blank,所以:

nil.blank? # => true
false.blank? # => true
true.blank? # => false
[].blank?      # => true
[1,2,3].blank? # => false
{}.blank?                # => true
{ key: 'value' }.blank?  # => false
''.blank?       # => true
'   '.blank?    # => true
"\t\n\r".blank? # => true
' blah '.blank? # => false
"\u00a0".blank? # => true
1.blank? # => false
0.blank? # => false
Time.now.blank? # => false

教材5-4 Step 3: 购物车设计 Part 2用到blank的是这一段:

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base

 # ...略



+  helper_method :current_cart

+  def current_cart
+    @current_cart ||= find_cart
+  end

+  private

+  def find_cart
+    cart = Cart.find_by(id: session[:cart_id])
+    if cart.blank?
+      cart = Cart.create
+    end
+    session[:cart_id] = cart.id
+    return cart
+  end
end

即这三句:

+    if cart.blank?
+      cart = Cart.create
+    end

它的意思是说,如果cart为空,那么就创建一个cart。因为cart为空时,cart.blank?的值为true,这时if语句才会继续往下执行cart = Cart.create;cart不为空时,cart.blank?的值为false,这时就不会到if内部去,而跳到if的下一句session[:cart_id] = cart.id了。

Comments

comments powered by Disqus