Class: Object
- Inherits:
- BasicObject
- Defined in:
- lib/extend/object.rb
Overview
Borrowed from Rails source
Instance Method Summary collapse
-
#blank? ⇒ true, false
An object is blank if it’s false, empty, or a whitespace string.
-
#presence ⇒ Object
Returns the receiver if it’s present otherwise returns
nil
. -
#present? ⇒ true, false
An object is present if it’s not blank.
-
#to_param ⇒ Object
Alias of
to_s
. -
#to_query(key) ⇒ Object
Converts an object into a string suitable for use as a URL query string, using the given
key
as the param name.
Instance Method Details
#blank? ⇒ true, false
An object is blank if it’s false, empty, or a whitespace string. For example, ”, ‘ ’, nil
, [], and {} are all blank.
This simplifies
address.nil? || address.empty?
to
address.blank?
27 28 29 |
# File 'lib/extend/object.rb', line 27 def blank? respond_to?(:empty?) ? !!empty? : !self end |
#presence ⇒ Object
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'
54 55 56 |
# File 'lib/extend/object.rb', line 54 def presence self if present? end |
#present? ⇒ true, false
An object is present if it’s not blank.
34 35 36 |
# File 'lib/extend/object.rb', line 34 def present? !blank? end |
#to_query(key) ⇒ Object
Converts an object into a string suitable for use as a URL query string, using the given key
as the param name.
11 12 13 |
# File 'lib/extend/object.rb', line 11 def to_query(key) "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}" end |