class Object
def `(command) #:nodoc:
Unix on the former but not the latter.
spawned shell prints a message to stderr and sets $?. We emulate
On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the
Makes backticks behave (somewhat more) similarly on all platforms.
def `(command) #:nodoc: super rescue Errno::ENOENT => e STDERR.puts "#$0: #{e}" end
def acts_like?(duck)
x.acts_like?(:date) to do duck-type-safe comparisons, since classes that
acts_like_time?. As a result, we can do x.acts_like?(:time) and
to define an acts_like_date? method, and extends Time to define
A duck-type assistant method. For example, Active Support extends Date
def acts_like?(duck) respond_to? :"acts_like_#{duck}?" end
def as_json(options = nil) #:nodoc:
def as_json(options = nil) #:nodoc: if respond_to?(:to_hash) to_hash else instance_values end end
def blank?
...to:
if address.nil? || address.empty?
This simplifies:
For example, '', ' ', +nil+, [], and {} are all blank.
An object is blank if it's false, empty, or a whitespace string.
def blank? respond_to?(:empty?) ? empty? : !self end
def deep_dup
object.instance_variable_defined?(:@a) #=> false
dup.instance_variable_set(:@a, 1)
dup = object.deep_dup
object = Object.new
not duplicable, returns +self+.
Returns a deep copy of object if it's duplicable. If it's
def deep_dup duplicable? ? dup : self end
def duplicable?
False for +nil+, +false+, +true+, symbol, and number objects;
Can you safely dup this object?
def duplicable? true end
def html_safe?
def html_safe? false end
def in?(*args)
This will throw an ArgumentError if the argument doesn't respond
"Konata".in?(characters) # => true
characters = ["Konata", "Kagami", "Tsukasa"]
any object which responds to +#include?+. Usage:
Returns true if this object is included in the argument. Argument must be
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
def instance_values
end
end
@x, @y = x, y
def initialize(x, y)
class C
corresponding values.
Returns a hash with string keys that maps instance variable names without "@" to their
def instance_values Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }] end
def instance_variable_names
end
end
@x, @y = x, y
def initialize(x, y)
class C
Returns an array of instance variable names as strings including "@".
def instance_variable_names instance_variables.map { |var| var.to_s } end
def presence
...becomes:
region = state || country || 'US'
country = params[:country] if params[:country].present?
state = params[:state] if params[:state].present?
HTTP POST/query parameters:
as not present at all. For example, this simplifies a common check for
This is handy for any representation of objects where blank is the same
object.presence is equivalent to object.present? ? object : nil.
Returns object if it's present? otherwise returns +nil+.
def presence self if present? end
def present?
def present? !blank? end
def to_param
def to_param to_s end
def to_query(key)
Converts an object into a string suitable for use as a URL query string,
def to_query(key) require 'cgi' unless defined?(CGI) && defined?(CGI::escape) "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}" end
def try(*a, &b)
+SimpleDelegator+ will delegate +try+ to the target instead of calling it on
like direct subclasses of +BasicObject+. For example, using +try+ with
with instances of classes that do not have +Object+ among their ancestors,
Please also note that +try+ is defined on +Object+, therefore it won't work
end
...
@person.try do |p|
block unless it is +nil+:
If +try+ is called without arguments it yields the receiver to a given
otherwise.
to the method the call is attempted and +ArgumentError+ is still raised
The number of arguments in the signature must match. If the object responds
end
...
@posts.try(:each_slice, 2) do |a, b|
Arguments and blocks are forwarded to the method if invoked:
nil.try(:to_i) # => nil, rather than 0
to the method:
+try+ returns +nil+ when called on +nil+ regardless of whether it responds
@person ? @person.name : nil
instead of
@person.try(:name)
This method is defined to be able to write
call returns +nil+ rather than raising an exception.
+public_send+ does, except that if the receiver does not respond to it the
Invokes the public method whose name goes as first argument just like
def try(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) if respond_to?(a.first) end end
def try!(*a, &b)
Same as #try, but will raise a NoMethodError exception if the receiving is not nil and
def try!(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) end end
def with_options(options)
with_options can also be nested since the call is forwarded to its receiver.
end
body i18n.t :body, user_name: user.name
subject i18n.t :subject
I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n|
It can also be used with an explicit receiver:
end
end
assoc.has_many :expenses
assoc.has_many :invoices
assoc.has_many :products
assoc.has_many :customers
with_options dependent: :destroy do |assoc|
class Account < ActiveRecord::Base
Using with_options, we can remove the duplication:
end
has_many :expenses, dependent: :destroy
has_many :invoices, dependent: :destroy
has_many :products, dependent: :destroy
has_many :customers, dependent: :destroy
class Account < ActiveRecord::Base
Without with_options>, this code contains duplication:
hash as its final argument.
provided. Each method called on the block variable must take an options
the receiver, will have its options merged with the default +options+ hash
method calls. Each method called in the block, with the block variable as
An elegant way to factor duplication out of options passed to a series of
def with_options(options) yield ActiveSupport::OptionMerger.new(self, options) end