Class: Object

Inherits:
BasicObject
Includes:
ActiveSupport::Dependencies::RequireDependency, ActiveSupport::Tryable, LateObject, Minitest::Expectations
Defined in:
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/builder-3.2.4/lib/blankslate.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/builder-3.2.4/test/preload.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/minitest-5.17.0/lib/minitest/mock.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/minitest-5.17.0/lib/minitest/spec.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/builder-3.2.4/test/test_blankslate.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/pry-0.14.2/lib/pry/core_extensions.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/minitest-5.17.0/test/minitest/test_minitest_mock.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/try.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/json.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/blank.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/deep_dup.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/to_query.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/acts_like.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/inclusion.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/duplicable.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/with_options.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/string/output_safety.rb,
lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/instance_variables.rb

Overview

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

method(:puts).dup # => TypeError: allocator undefined for Method

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. ++

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ActiveSupport::Tryable

#try, #try!

Methods included from LateObject

included, #late_object

Methods included from Minitest::Expectations

#assert_empty, #assert_equal, #assert_in_delta, #assert_in_epsilon, #assert_includes, #assert_instance_of, #assert_kind_of, #assert_match, #assert_nil, #assert_operator, #assert_output, #assert_path_exists, #assert_raises, #assert_respond_to, #assert_same, #assert_silent, #assert_throws, #refute_empty, #refute_equal, #refute_in_delta, #refute_in_epsilon, #refute_includes, #refute_instance_of, #refute_kind_of, #refute_match, #refute_nil, #refute_operator, #refute_path_exists, #refute_respond_to, #refute_same

Methods included from ActiveSupport::Dependencies::RequireDependency

#require_dependency

Class Attribute Details

.o_added_namesObject (readonly)

Returns the value of attribute o_added_names.



32
33
34
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/builder-3.2.4/test/preload.rb', line 32

def o_added_names
  @o_added_names
end

Class Method Details

.blank_slate_method_addedObject



104
105
106
107
108
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/builder-3.2.4/lib/blankslate.rb', line 104

def method_added(name)
  preload_method_added(name)
  @o_added_names ||= []
  @o_added_names << name
end

.find_hidden_method(name) ⇒ Object



115
116
117
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/builder-3.2.4/lib/blankslate.rb', line 115

def find_hidden_method(name)
  nil
end

.method_added(name) ⇒ Object

Detect method additions to Object and remove them in the BlankSlate class.



108
109
110
111
112
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/builder-3.2.4/lib/blankslate.rb', line 108

def method_added(name)
  preload_method_added(name)
  @o_added_names ||= []
  @o_added_names << name
end

.preload_method_addedObject



33
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/builder-3.2.4/test/preload.rb', line 33

alias_method :preload_method_added, :method_added

Instance Method Details

#__binding__Binding

Return a binding object for the receiver.

The ‘self` of the binding is set to the current object, and it contains no local variables.

The default definee (yugui.jp/articles/846) is set such that:

  • If ‘self` is a class or module, then new methods created in the binding will be defined in that class or module (as in `class Foo; end`).

  • If ‘self` is a normal object, then new methods created in the binding will be defined on its singleton class (as in `class << self; end`).

  • If ‘self` doesn’t have a real singleton class (i.e. it is a Fixnum, Float, Symbol, nil, true, or false), then new methods will be created on the object’s class (as in ‘self.class.class_eval{ }`)

Newly created constants, including classes and modules, will also be added to the default definee.

Returns:

  • (Binding)


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/pry-0.14.2/lib/pry/core_extensions.rb', line 70

def __binding__
  # If you ever feel like changing this method, be careful about variables
  # that you use. They shouldn't be inserted into the binding that will
  # eventually be returned.

  # When you're cd'd into a class, methods you define should be added to it.
  if is_a?(Module)
    # A special case, for JRuby.
    # Module.new.class_eval("binding") has different behaviour than CRuby,
    # where this is not needed: class_eval("binding") vs class_eval{binding}.
    # Using a block works around the difference of behaviour on JRuby.
    # The scope is clear of local variables. Don't add any.
    #
    # This fixes the following two spec failures, at https://travis-ci.org/pry/pry/jobs/274470002
    # 1) ./spec/pry_spec.rb:360:in `block in (root)'
    # 2) ./spec/pry_spec.rb:366:in `block in (root)'
    return class_eval { binding } if Pry::Helpers::Platform.jruby? && name.nil?

    # class_eval sets both self and the default definee to this class.
    return class_eval("binding", __FILE__, __LINE__)
  end

  unless self.class.method_defined?(:__pry__)
    # The easiest way to check whether an object has a working singleton class
    # is to try and define a method on it. (just checking for the presence of
    # the singleton class gives false positives for `true` and `false`).
    # __pry__ is just the closest method we have to hand, and using
    # it has the nice property that we can memoize this check.
    begin
      # instance_eval sets the default definee to the object's singleton class
      instance_eval(*Pry::BINDING_METHOD_IMPL)

    # If we can't define methods on the Object's singleton_class. Then we fall
    # back to setting the default definee to be the Object's class. That seems
    # nicer than having a REPL in which you can't define methods.
    rescue TypeError, Pry::FrozenObjectException
      # class_eval sets the default definee to self.class
      self.class.class_eval(*Pry::BINDING_METHOD_IMPL)
    end
  end

  __pry__
end

#acts_like?(duck) ⇒ Boolean

Provides a way to check whether some class acts like some other class based on the existence of an appropriately-named marker method.

A class that provides the same interface as SomeClass may define a marker method named acts_like_some_class? to signal its compatibility to callers of acts_like?(:some_class).

For example, Active Support extends Date to define an acts_like_date? method, and extends Time to define acts_like_time?. As a result, developers can call x.acts_like?(:time) and x.acts_like?(:date) to test duck-type compatibility, and classes that are able to act like Time can also define an acts_like_time? method to interoperate.

Note that the marker method is only expected to exist. It isn’t called, so its body or return value are irrelevant.

Example: A class that provides the same interface as String

This class may define:

class Stringish
  def acts_like_string?
  end
end

Then client code can query for duck-type-safeness this way:

Stringish.new.acts_like?(:string) # => true

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/acts_like.rb', line 33

def acts_like?(duck)
  case duck
  when :time
    respond_to? :acts_like_time?
  when :date
    respond_to? :acts_like_date?
  when :string
    respond_to? :acts_like_string?
  else
    respond_to? :"acts_like_#{duck}?"
  end
end

#another_late_additionObject



60
61
62
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/builder-3.2.4/test/test_blankslate.rb', line 60

def another_late_addition
  4321
end

#as_json(options = nil) ⇒ Object

:nodoc:



59
60
61
62
63
64
65
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/json.rb', line 59

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

#blank?true, false

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

This simplifies

!address || address.empty?

to

address.blank?

Returns:

  • (true, false)


18
19
20
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/blank.rb', line 18

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

#deep_dupObject

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


15
16
17
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/deep_dup.rb', line 15

def deep_dup
  duplicable? ? dup : self
end

#duplicable?Boolean

Can you safely dup this object?

False for method objects; true otherwise.

Returns:

  • (Boolean)


26
27
28
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/duplicable.rb', line 26

def duplicable?
  true
end

#html_safe?Boolean

Returns:

  • (Boolean)


150
151
152
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/string/output_safety.rb', line 150

def html_safe?
  false
end

#in?(another_object) ⇒ Boolean

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?.

Returns:

  • (Boolean)


12
13
14
15
16
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/inclusion.rb', line 12

def in?(another_object)
  another_object.include?(self)
rescue NoMethodError
  raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
end

#instance_valuesObject

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}


14
15
16
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/instance_variables.rb', line 14

def instance_values
  Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }]
end

#instance_variable_namesObject

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"]


27
28
29
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/instance_variables.rb', line 27

def instance_variable_names
  instance_variables.map(&:to_s)
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'

Returns:



45
46
47
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/blank.rb', line 45

def presence
  self if present?
end

#presence_in(another_object) ⇒ Object

Returns the receiver if it’s included in the argument otherwise returns nil. Argument must be any object which responds to #include?. Usage:

params[:bucket_type].presence_in %w( project calendar )

This will throw an ArgumentError if the argument doesn’t respond to #include?.

Returns:



26
27
28
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/inclusion.rb', line 26

def presence_in(another_object)
  in?(another_object) ? self : nil
end

#present?true, false

An object is present if it’s not blank.

Returns:

  • (true, false)


25
26
27
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/blank.rb', line 25

def present?
  !blank?
end

#pry(object = nil, hash = {}) ⇒ Object

Start a Pry REPL on self.

If ‘self` is a Binding then that will be used to evaluate expressions; otherwise a new binding will be created.

Examples:

With a binding

binding.pry

On any object

"dummy".pry

With options

def my_method
  binding.pry :quiet => true
end
my_method()

Parameters:

  • object (Object) (defaults to: nil)

    the object or binding to pry (__deprecated__, use ‘object.pry`)

  • hash (Hash) (defaults to: {})

    the options hash

See Also:



43
44
45
46
47
48
49
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/pry-0.14.2/lib/pry/core_extensions.rb', line 43

def pry(object = nil, hash = {})
  if object.nil? || Hash === object # rubocop:disable Style/CaseEquality
    Pry.start(self, object || {})
  else
    Pry.start(object, hash)
  end
end

#stub(name, val_or_callable, *block_args, **block_kwargs, &block) ⇒ Object Also known as: stub5, stub6

Add a temporary stubbed method replacing name for the duration of the block. If val_or_callable responds to #call, then it returns the result of calling it, otherwise returns the value as-is. If stubbed method yields a block, block_args will be passed along. Cleans up the stub at the end of the block. The method name must exist before stubbing.

def test_stale_eh
  obj_under_test = Something.new
  refute obj_under_test.stale?

  Time.stub :now, Time.at(0) do
    assert obj_under_test.stale?
  end
end

– NOTE: keyword args in callables are NOT checked for correctness against the existing method. Too many edge cases to be worth it.



278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/minitest-5.17.0/lib/minitest/mock.rb', line 278

def stub name, val_or_callable, *block_args, **block_kwargs, &block
  new_name = "__minitest_stub__#{name}"

  metaclass = class << self; self; end

  if respond_to? name and not methods.map(&:to_s).include? name.to_s then
    metaclass.send :define_method, name do |*args, **kwargs|
      super(*args, **kwargs)
    end
  end

  metaclass.send :alias_method, new_name, name

  if ENV["MT_KWARGS_HAC\K"] then
    metaclass.send :define_method, name do |*args, &blk|
      if val_or_callable.respond_to? :call then
        val_or_callable.call(*args, &blk)
      else
        blk.call(*block_args, **block_kwargs) if blk
        val_or_callable
      end
    end
  else
    metaclass.send :define_method, name do |*args, **kwargs, &blk|
      if val_or_callable.respond_to? :call then
        if kwargs.empty? then # FIX: drop this after 2.7 dead
          val_or_callable.call(*args, &blk)
        else
          val_or_callable.call(*args, **kwargs, &blk)
        end
      else
        if blk then
          if block_kwargs.empty? then # FIX: drop this after 2.7 dead
            blk.call(*block_args)
          else
            blk.call(*block_args, **block_kwargs)
          end
        end
        val_or_callable
      end
    end
  end

  block[self]
ensure
  metaclass.send :undef_method, name
  metaclass.send :alias_method, name, new_name
  metaclass.send :undef_method, new_name
end

#to_paramObject

Alias of to_s.



7
8
9
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/to_query.rb', line 7

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.



13
14
15
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/to_query.rb', line 13

def to_query(key)
  "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
end

#with_options(options, &block) ⇒ 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

When you don’t pass an explicit receiver, it executes the whole block in merging options context:

class Account < ActiveRecord::Base
  with_options dependent: :destroy do
    has_many :customers
    has_many :products
    has_many :invoices
    has_many :expenses
  end
end

with_options can also be nested since the call is forwarded to its receiver.

NOTE: Each nesting level will merge inherited defaults in addition to their own.

class Post < ActiveRecord::Base
  with_options if: :persisted?, length: { minimum: 50 } do
    validates :content, if: -> { content.present? }
  end
end

The code is equivalent to:

validates :content, length: { minimum: 50 }, if: -> { content.present? }

Hence the inherited default for if key is ignored.

NOTE: You cannot call class methods implicitly inside of with_options. You can access these methods using the class name instead:

class Phone < ActiveRecord::Base
  enum phone_number_type: { home: 0, office: 1, mobile: 2 }

  with_options presence: true do
    validates :phone_number_type, inclusion: { in: Phone.phone_number_types.keys }
  end
end

When the block argument is omitted, the decorated Object instance is returned:

module MyStyledHelpers
  def styled
    with_options style: "color: red;"
  end
end

# styled.link_to "I'm red", "/"
# #=> <a href="/" style="color: red;">I'm red</a>

# styled.button_tag "I'm red too!"
# #=> <button style="color: red;">I'm red too!</button>


92
93
94
95
96
97
98
99
100
# File 'lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/activesupport-7.0.4/lib/active_support/core_ext/object/with_options.rb', line 92

def with_options(options, &block)
  option_merger = ActiveSupport::OptionMerger.new(self, options)

  if block
    block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger)
  else
    option_merger
  end
end