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.
# File lib/active_support/core_ext/object/acts_like.rb, line 7 def acts_like?(duck) respond_to? :"acts_like_#{duck}?" end
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?
# File lib/active_support/core_ext/object/blank.rb, line 13 def blank? respond_to?(:empty?) ? empty? : !self end
Returns a deep copy of object if it's duplicable. If it's not
duplicable, returns self
.
object = Object.new dup = object.deep_dup dup.instance_variable_set(:@a, 1) object.instance_variable_defined?(:@a) #=> false dup.instance_variable_defined?(:@a) #=> true
# File lib/active_support/core_ext/object/deep_dup.rb, line 13 def deep_dup duplicable? ? dup : self end
Can you safely dup this object?
False for nil
, false
, true
, symbol,
and number objects; true otherwise.
# File lib/active_support/core_ext/object/duplicable.rb, line 24 def duplicable? true end
# File lib/active_support/core_ext/string/output_safety.rb, line 72 def html_safe? false end
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?
.
# File lib/active_support/core_ext/object/inclusion.rb, line 12 def in?(*args) if args.length > 1 ActiveSupport::Deprecation.warn "Calling #in? with multiple arguments is" " deprecated, please pass in an object that responds to #include? instead." 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
Returns a hash with string keys that maps instance variable names without “@” to their corresponding values.
class C def initialize(x, y) @x, @y = x, y end end C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
# File lib/active_support/core_ext/object/instance_variables.rb, line 12 def instance_values Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }] end
Returns an array of instance variable names as strings including “@”.
class C def initialize(x, y) @x, @y = x, y end end C.new(0, 1).instance_variable_names # => ["@y", "@x"]
# File lib/active_support/core_ext/object/instance_variables.rb, line 25 def instance_variable_names instance_variables.map { |var| var.to_s } end
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'
# File lib/active_support/core_ext/object/blank.rb, line 36 def presence self if present? end
An object is present if it's not blank?
.
# File lib/active_support/core_ext/object/blank.rb, line 18 def present? !blank? end
Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
# File lib/active_support/core_ext/object/to_json.rb, line 15 def to_json(options = nil) ActiveSupport::JSON.encode(self, options) end
Alias of to_s
.
# File lib/active_support/core_ext/object/to_param.rb, line 3 def to_param to_s end
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.
# 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
Invokes the public method whose name goes as first argument just like
public_send
does, except that if the receiver does not respond
to it the call returns nil
rather than raising an exception.
This method is defined to be able to write
@person.try(:name)
instead of
@person ? @person.name : nil
try
returns nil
when called on nil
regardless of whether it responds to the method:
nil.try(:to_i) # => nil, rather than 0
Arguments and blocks are forwarded to the method if invoked:
@posts.try(:each_slice, 2) do |a, b| ... end
The number of arguments in the signature must match. If the object responds
to the method the call is attempted and ArgumentError
is still
raised otherwise.
If try
is called without arguments it yields the receiver to a
given block unless it is nil
:
@person.try do |p| ... end
Please also note that try
is defined on Object
,
therefore it won't work with instances of classes that do not have
Object
among their ancestors, like direct subclasses of
BasicObject
. For example, using try
with
SimpleDelegator
will delegate try
to the target
instead of calling it on delegator itself.
# File lib/active_support/core_ext/object/try.rb, line 41 def try(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) if respond_to?(a.first) end end
Same as try, but will raise a NoMethodError exception if the receiving is not nil and does not implemented the tried method.
# File lib/active_support/core_ext/object/try.rb, line 51 def try!(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) end end
# File lib/active_support/core_ext/uri.rb, line 9 def unescape(str, escaped = /%[a-fA-F\d]{2}/) # TODO: Are we actually sure that ASCII == UTF-8? # YK: My initial experiments say yes, but let's be sure please enc = str.encoding enc = Encoding::UTF_8 if enc == Encoding::US_ASCII str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc) end
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.
# File lib/active_support/core_ext/object/with_options.rb, line 39 def with_options(options) yield ActiveSupport::OptionMerger.new(self, options) end