Skip to content

Instantly share code, notes, and snippets.

@sahilshah-rr
Last active June 7, 2017 22:32
Show Gist options
  • Save sahilshah-rr/4168b0b0b39a98ea9d4e38e69a33a8f6 to your computer and use it in GitHub Desktop.
Save sahilshah-rr/4168b0b0b39a98ea9d4e38e69a33a8f6 to your computer and use it in GitHub Desktop.
Ruby: Non-instantiable parent class with instantiable subclasses
class AlternateParent
def self.new(*args)
raise NoMethodError, "cannot instantiate #{self.name}" if self == AlternateParent
super
end
def initialize(num)
@num = num
end
end
class AlternateSubClass < AlternateParent
def initialize(num)
super
@sub_num = num * num
end
end
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>
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
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