Class: Object
- Inherits:
- BasicObject
- Defined in:
- lib/core_ext/blank.rb,
lib/core_ext/object.rb
Overview
reopening Object class
Instance Method Summary collapse
-
#blank? ⇒ true, false
Checks if an object is blank or not.
-
#in?(another_object) ⇒ Boolean
Returns true if this object is included in the argument.
-
#presence ⇒ Object?
Returns self if the object is present, otherwise returns nil.
-
#presence_in(another_object) ⇒ Object
Returns the receiver if it’s included in the argument otherwise returns
nil. -
#present? ⇒ true, false
Returns true if the object is not blank.
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?
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?.
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 |
#presence ⇒ Object?
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'
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?.
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.
23 24 25 |
# File 'lib/core_ext/blank.rb', line 23 def present? !blank? end |