Class: Object

Inherits:
BasicObject
Defined in:
lib/active_support/core_ext/object/duplicable.rb,
lib/active_support/json/encoding.rb,
lib/active_support/core_ext/object/try.rb,
lib/active_support/core_ext/object/blank.rb,
lib/active_support/core_ext/object/to_param.rb,
lib/active_support/core_ext/object/to_query.rb,
lib/active_support/core_ext/kernel/agnostics.rb,
lib/active_support/core_ext/object/acts_like.rb,
lib/active_support/core_ext/object/inclusion.rb,
lib/active_support/core_ext/object/with_options.rb,
lib/active_support/core_ext/string/output_safety.rb,
lib/active_support/core_ext/object/instance_variables.rb

Overview

– Most objects are cloneable, but not all. For example you can’t dup nil:

nil.dup # => TypeError: can't dup NilClass

Classes may signal their instances are not duplicable removing dup/clone or raising exceptions from them. So, to dup an arbitrary object you normally use an optimistic approach and are ready to catch an exception, say:

arbitrary_object.dup rescue object

Rails dups objects in a few critical spots where they are not that arbitrary. That rescue is very expensive (like 40 times slower than a predicate), and it is often triggered.

That’s why we hardcode the following cases and check duplicable? instead of using that rescue idiom. ++

Instance Method Summary collapse

Instance Method Details

#`(command) ⇒ Object

Makes backticks behave (somewhat more) similarly on all platforms. On win32 ‘nonexistent_command` raises Errno::ENOENT; on Unix, the spawned shell prints a message to stderr and sets $?. We emulate Unix on the former but not the latter.



6
7
8
9
10
# File 'lib/active_support/core_ext/kernel/agnostics.rb', line 6

def `(command) #:nodoc:
  super
rescue Errno::ENOENT => e
  STDERR.puts "#$0: #{e}"
end

#acts_like?(duck) ⇒ Boolean

A duck-type assistant method. For example, Active Support extends Date to define an acts_like_date? method, and extends Time to define acts_like_time?. As a result, we can do “x.acts_like?(:time)” and “x.acts_like?(:date)” to do duck-type-safe comparisons, since classes that we want to act like Time simply need to define an acts_like_time? method.

Returns:

  • (Boolean)


7
8
9
# File 'lib/active_support/core_ext/object/acts_like.rb', line 7

def acts_like?(duck)
  respond_to? :"acts_like_#{duck}?"
end

#as_json(options = nil) ⇒ Object

:nodoc:



145
146
147
148
149
150
151
# File 'lib/active_support/json/encoding.rb', line 145

def as_json(options = nil) #:nodoc:
  if respond_to?(:to_hash)
    to_hash
  else
    instance_values
  end
end

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


15
16
17
# File 'lib/active_support/core_ext/object/blank.rb', line 15

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

#duplicable?Boolean

Can you safely dup this object?

False for nil, false, true, symbols, numbers, class and module objects; true otherwise.

Returns:

  • (Boolean)


24
25
26
# File 'lib/active_support/core_ext/object/duplicable.rb', line 24

def duplicable?
  true
end

#html_safe?Boolean

Returns:

  • (Boolean)


76
77
78
# File 'lib/active_support/core_ext/string/output_safety.rb', line 76

def html_safe?
  false
end

#in?(*args) ⇒ Boolean

Returns true if this object is included in the argument(s). Argument must be any object which responds to #include? or optionally, multiple arguments can be passed in. Usage:

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true

character = "Konata"
character.in?("Konata", "Kagami", "Tsukasa") # => true

This will throw an ArgumentError if a single argument is passed in and it doesn’t respond to #include?.

Returns:

  • (Boolean)


13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/active_support/core_ext/object/inclusion.rb', line 13

def in?(*args)
  if args.length > 1
    args.include? self
  else
    another_object = args.first
    if another_object.respond_to? :include?
      another_object.include? self
    else
      raise ArgumentError.new("The single parameter passed to #in? must respond to #include?")
    end
  end
end

#instance_valuesObject

Returns a hash that maps instance variable names without “@” to their corresponding values. Keys are strings both in Ruby 1.8 and 1.9.

class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}


12
13
14
# File 'lib/active_support/core_ext/object/instance_variables.rb', line 12

def instance_values #:nodoc:
  Hash[instance_variables.map { |name| [name.to_s[1..-1], instance_variable_get(name)] }]
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'


38
39
40
# File 'lib/active_support/core_ext/object/blank.rb', line 38

def presence
  self if present?
end

#present?Boolean

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

Returns:

  • (Boolean)


20
21
22
# File 'lib/active_support/core_ext/object/blank.rb', line 20

def present?
  !blank?
end

#to_paramObject

Alias of to_s.



3
4
5
# File 'lib/active_support/core_ext/object/to_param.rb', line 3

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.



8
9
10
11
# File 'lib/active_support/core_ext/object/to_query.rb', line 8

def to_query(key)
  require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
  "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
end

#try(*a, &b) ⇒ Object

Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does.

Unlike that method however, a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass.

If try is called without a method to call, it will yield any given block with the object.

Please also note that try is defined on Object, therefore it won’t work with subclasses of BasicObject. For example, using try with SimpleDelegator will delegate try to target instead of calling it on delegator itself.

Examples

Without try

@person && @person.name

or

@person ? @person.name : nil

With try

@person.try(:name)

try also accepts arguments and/or a block, for the method it is trying

Person.try(:find, 1)
@people.try(:collect) {|p| p.name}

Without a method argument try will yield to the block unless the receiver is nil.

@person.try { |p| "#{p.first_name} #{p.last_name}" }

try behaves like Object#send, unless called on NilClass.



32
33
34
35
36
37
38
# File 'lib/active_support/core_ext/object/try.rb', line 32

def try(*a, &b)
  if a.empty? && block_given?
    yield self
  else
    __send__(*a, &b)
  end
end

#with_options(options) {|ActiveSupport::OptionMerger.new(self, options)| ... } ⇒ Object

An elegant way to factor duplication out of options passed to a series of method calls. Each method called in the block, with the block variable as the receiver, will have its options merged with the default options hash provided. Each method called on the block variable must take an options hash as its final argument.

Without with_options>, this code contains duplication:

class Account < ActiveRecord::Base
  has_many :customers, :dependent => :destroy
  has_many :products,  :dependent => :destroy
  has_many :invoices,  :dependent => :destroy
  has_many :expenses,  :dependent => :destroy
end

Using with_options, we can remove the duplication:

class Account < ActiveRecord::Base
  with_options :dependent => :destroy do |assoc|
    assoc.has_many :customers
    assoc.has_many :products
    assoc.has_many :invoices
    assoc.has_many :expenses
  end
end

It can also be used with an explicit receiver:

I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
  subject i18n.t :subject
  body    i18n.t :body, :user_name => user.name
end

with_options can also be nested since the call is forwarded to its receiver. Each nesting level will merge inherited defaults in addition to their own.

Yields:



40
41
42
# File 'lib/active_support/core_ext/object/with_options.rb', line 40

def with_options(options)
  yield ActiveSupport::OptionMerger.new(self, options)
end