Last active
June 7, 2017 22:32
-
-
Save sahilshah-rr/4168b0b0b39a98ea9d4e38e69a33a8f6 to your computer and use it in GitHub Desktop.
Ruby: Non-instantiable parent class with instantiable subclasses
This file contains 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
class AlternateParent | |
def self.new(*args) | |
raise NoMethodError, "cannot instantiate #{self.name}" if self == AlternateParent | |
super | |
end | |
def initialize(num) | |
@num = num | |
end | |
end |
This file contains 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
class AlternateSubClass < AlternateParent | |
def initialize(num) | |
super | |
@sub_num = num * num | |
end | |
end |
This file contains 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
Parent.new(5) | |
# NoMethodError: undefined method `new' for Parent:Class | |
SubClass.new(5) | |
#<SubClass:0x007fcfde857950 @num=5, @sub_num=25> | |
AlternateParent.new(5) | |
# NoMethodError: cannot instantiate AlternateParent | |
AlternateSubClass.new(5) | |
#<AlternateSubClass:0x007fcfde8565c8 @num=5, @sub_num=25> |
This file contains 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
class Parent | |
class << self | |
undef_method :new | |
def inherited(sub_class) | |
sub_class.define_singleton_method(:new) do |*args| | |
Class.instance_method(:new).bind(sub_class).call(*args) | |
end | |
end | |
end | |
def initialize(num) | |
@num = num | |
end | |
end |
This file contains 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
class SubClass < Parent | |
def initialize(num) | |
super | |
@sub_num = num * num | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment