Class: Object

Inherits:
BasicObject
Defined in:
lib/nyara/patches/blank.rb,
lib/nyara/patches/to_query.rb,
lib/nyara/patches/to_query.rb

Overview

Copyright (c) 2005-2013 David Heinemeier Hansson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Instance Method Summary collapse

Instance Method Details

#blank?Boolean

An object is blank if it's false, empty, or a whitespace string. For example, '', ' ', +nil+, [], and {} are all blank.

This simplifies:

if address.nil? || address.empty?

...to:

if address.blank?

Returns:

  • (Boolean)

37
38
39
# File 'lib/nyara/patches/blank.rb', line 37

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

#presenceObject

Returns object if it's present? otherwise returns +nil+. object.presence is equivalent to object.present? ? object : nil.

This is handy for any representation of objects where blank is the same as not present at all. For example, this simplifies a common check for HTTP POST/query parameters:

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'


60
61
62
# File 'lib/nyara/patches/blank.rb', line 60

def presence
  self if present?
end

#present?Boolean

An object is present if it's not blank?.

Returns:

  • (Boolean)

42
43
44
# File 'lib/nyara/patches/blank.rb', line 42

def present?
  !blank?
end

#to_paramObject

Alias of to_s.


28
29
30
# File 'lib/nyara/patches/to_query.rb', line 28

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.

Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.


94
95
96
# File 'lib/nyara/patches/to_query.rb', line 94

def to_query(key)
  "#{Nyara::Ext.escape key.to_param, false}=#{Nyara::Ext.escape to_param.to_s, false}"
end