liveBook · Manning

Alias_method

As explained in The Well-Grounded Rubyist, Fourth Edition

alias_method is a private Module instance method that assigns an additional method name to an existing method using a symbol or string identifier.

Use alias_method to preserve an existing method under another name before redefining the original. It is a private Module instance method and accepts symbols or strings, unlike the alias keyword’s bare-name syntax. section 13.2.3

Logging through a pass-through override

A String#reverse override can print a message, call the aliased original method, and retain its return value. The resulting output is a log line followed by the reversed string. section 13.2.3

class String
  alias_method :__old_reverse__, :reverse
end

Compare alias_method :__old_reverse__, :reverse with the equivalent alias declaration for preserving the original implementation. section 13.2.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines method aliasing, argument forms, and its role in wrapping an original implementation, without exhaustive API coverage.
Examples
Demonstrates wrapping String#reverse with an aliased original that logs to STDERR before returning the reversed string.
What you can do after
Apply it to preserve an existing method while redefining the original for additional behavior.
How it connects
Connects method aliasing with the alias keyword, method overriding, pass-through overrides, logging, and debugging.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.