Class: Object

Inherits:
BasicObject
Defined in:
lib/core_ext/blank.rb,
lib/core_ext/object.rb

Overview

reopening Object class

Instance Method Summary collapse

Instance Method Details

#blank?true, false

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?

Returns:

  • (true, false)


16
17
18
# File 'lib/core_ext/blank.rb', line 16

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

#in?(another_object) ⇒ Boolean

Returns true if this object is included in the argument. Argument must be any object which responds to #include?. Usage:

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true

This will throw an ArgumentError if the argument doesn’t respond to #include?.

Returns:

  • (Boolean)


12
13
14
15
16
17
# File 'lib/core_ext/object.rb', line 12

def in?(another_object)
  another_object.include?(self)
rescue NoMethodError
  # raise ArgumentError.new('The parameter passed to #in? must respond to #include?')
  raise(ArgumentError, 'The parameter passed to #in? must respond to #include?')
end

#presenceObject

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'

Returns:



43
44
45
# File 'lib/core_ext/blank.rb', line 43

def presence
  self if present?
end

#presence_in(another_object) ⇒ Object

Returns the receiver if it’s included in the argument otherwise returns nil. Argument must be any object which responds to #include?. Usage:

params[:bucket_type].presence_in %w( project calendar )

This will throw an ArgumentError if the argument doesn’t respond to #include?.

Returns:



27
28
29
# File 'lib/core_ext/object.rb', line 27

def presence_in(another_object)
  self.in?(another_object) ? self : nil
end

#present?true, false

An object is present if it’s not blank.

Returns:

  • (true, false)


23
24
25
# File 'lib/core_ext/blank.rb', line 23

def present?
  !blank?
end