Change the current context

# Grab an object
post = Post.last
# Get the post title
post.title # => post title

# 'cd' in to that object.
cd post

# Get the post title again without the 'post' reference
title # => post title

Temporary alter any method of the object

Example class:

class User < ApplicationRecord
  def perform_action
    some_callback
  end

  def some_callback
    puts "original callback"
  end
end

How to modified a method:

user = User.last

def user.some_callback
  puts "modified callback"
end

user.perform_action
# => "modified callback"

another_user = User.first
another_user.perform_action
# => "original callback"

Rendering the source of the method

$ post.title

# From: /home/adrian/.rvm/gems/ruby-3.4.2/gems/activemodel-8.0.2/lib/active_model/attribute_methods.rb:273

#         ActiveSupport::CodeGenerator.batch(generated_attribute_methods, __FILE__, __LINE__) do |owner|
#           attr_names.flatten.each do |attr_name|
#             define_attribute_method(attr_name, _owner: owner)
#             aliases_by_attribute_name[attr_name.to_s].each do |aliased_name|
#               generate_alias_attribute_methods owner, aliased_name, attr_name
#             end
#           end
#         end

👉 More tricks on Impactahead blog


📌 Hashrocket TIL