Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active April 8, 2023 02:53
Show Gist options
  • Save Integralist/1fbbe4dafc77200c0bed to your computer and use it in GitHub Desktop.
Save Integralist/1fbbe4dafc77200c0bed to your computer and use it in GitHub Desktop.
Ruby: override `new` constructor method using meta programming
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