Abstract Methods in Ruby
In order to create an abstract method of a class and let its subclass to fill in the blanks, you need to raise a NotImplementedError: as shown in the example below.
class MyClass
def my_method
raise NotImplementedError: new(“#{self.class.name} > my_method is not implemented”
end
end
class MySubclass < MyClass
def initialize(my_arg)
@my_arg = my_arg
end
def my_method
@my_arg*2
end
end
Ruby does not have built in abstract methods or classes the same way Java or C# have and does not enforce abstractedness the same way. So, NotImplementedError is kind of work around to provide you with the abstractedness that you may need. Moreover, Ruby is so relaxed that it will allow to instantiate class with only abstract methods and you’ll only be able to figure out it is an abstract or not by running into NotImplementedError message.
One way to deal with this lax of rules is to raise NotImplementedError message from within initialize method.
Another way of defining an abstract class is as follows
class MyClass
abstract :initialize, :my_method
end
class MySubclass < MyClass
def initialize
@type = :my_value
end
end
Be mindful that we only implemented initialize method and my_method is still an abstract method of our class.