开发者

Duplicating .blank? in standard Ruby

Rails has a .blank? method that will return true if an Object is empty? or nil?. The actual code for this can be found here. When I try on 1.9.2 to duplicate this by doing:

class Object

  def blank?
    respond_to?(:empty?) ? empty? : !self
  end

end

Calling "".blank? returns true but calling " ".blank? returns false when according to the rails documentation a whitespace string should eval to true for .blank? Before I looked up the code I originally wrote:

class Obje开发者_如何学JAVAct

  def blank?
    !!self.empty? || !!self.nil?
  end

end

and had the same results. What am I missing?


You forget about this - https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/blank.rb#L95

class String
  # A string is blank if it's empty or contains whitespaces only:
  #
  #   "".blank?                 # => true
  #   "   ".blank?              # => true
  #   " something here ".blank? # => false
  #
  def blank?
    self !~ /\S/
  end
end


The String class overrides the Object implementation of blank? in Rails's implementation:

class String

  def blank?
    # Blank if this String is not composed of characters other than whitespace.
    self !~ /\S/ 
  end

end


Strings are not classed as empty? if they are full of spaces only

>> "  ".empty?
=> false

Therefore, you may wish to also create

class String
  def blank?
    strip.empty?
  end
end

But think carefully about this - monkey patching like this is hazardous, especially if other modules will use your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜