Class: Object

Inherits:
BasicObject
Defined in:
lib/extend/object.rb

Overview

Borrowed from Rails source

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, ”, ‘ ’, 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

#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'


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_paramObject

Alias of to_s.



5
6
7
# File 'lib/extend/object.rb', line 5

def to_param
  to_s
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