Last active
April 8, 2023 02:53
-
-
Save Integralist/1fbbe4dafc77200c0bed to your computer and use it in GitHub Desktop.
Ruby: override `new` constructor method using meta programming
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Bar | |
module ClassMethods | |
# `new` is a class method on the `Class` object | |
# It then uses `send` to access `initialize` which would otherwise be a private instance method | |
# So it can be overridden by extending the your class with a new `new` class method | |
def new(*args, &block) | |
super | |
p "new constructor defined" | |
end | |
end | |
class << self | |
def included(klass) | |
p "#{klass} is the class that's including #{self}" | |
klass.extend(ClassMethods) | |
end | |
end | |
end | |
class Foo | |
include Bar | |
def initialize | |
p "Foo constructor" | |
end | |
end | |
Foo.new | |
# "Foo is the class that's including Bar" | |
# "Foo constructor" | |
# "new constructor defined" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment