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

Checks if an object is blank or not. An object is blank if it does not respond to empty? or if it returns false on calling empty?. If it does not respond to empty?, then it will check if the object is truthy.

This simplifies ‘!address || address.empty?` to address.blank?

Returns:

  • (true, false)

    false if object responds to empty? and empty? returns false, true otherwise



14
15
16
# File 'lib/core_ext/blank.rb', line 14

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)


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

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 self if the object is 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:

  • (Object, nil)

    self if present?, nil otherwise



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:



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

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

#present?true, false

Returns true if the object is not blank. An object is considered not blank if it has meaningful content.

Returns:

  • (true, false)

    true if object is not blank, false otherwise



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

def present?
  !blank?
end