K
kwatch
To define abstract method in Ruby, I use NotImplementedError like the
following:
----------
class Foo
def m1
raise NotImpelemntedError("#{self.class.name}#m1() is not
implemented.")
end
end
----------
I think it is convenient if the Module#abstract_method is defined.
----------
class Module
def abstract_method(*method_names)
method_names.each do |name|
s = <<-END
def #{name}
mesg = "\#{self.class.name}##{name}() is not implemented."
raise NotImplementedError.new(mesg)
end
END
module_eval s
end
end
class Foo
abstract_method :m1, :m2, :m3 # define abstract methods
end
obj = Foo.new
obj.m1 #=> Foo#m1() is not implemented yet. (NotImplementedError)
----------
But this solution doesn't allow us to define a method with arguments.
The following is another solution to define abstract method
which is able to define a method with arguments.
? example.rb
----------
module Abstract # or Module?
def not_implemented # or should_be_implemented?
backtrace = caller()
method_name = (backtrace.shift =~ /`(\w+)'$/) && $1
mesg = "#{self.class.name}##{method_name}() is not implemented."
err = NotImplementedError.new(mesg)
err.set_backtrace(backtrace)
raise err
end
end
class Foo
include Abstract
def m1(arg)
not_implemented
end
end
obj = Foo.new
p obj.m1('abc') #=> example.rb:20: Foo#m1() is not implemented.
(NotImplementedError)
following:
----------
class Foo
def m1
raise NotImpelemntedError("#{self.class.name}#m1() is not
implemented.")
end
end
----------
I think it is convenient if the Module#abstract_method is defined.
----------
class Module
def abstract_method(*method_names)
method_names.each do |name|
s = <<-END
def #{name}
mesg = "\#{self.class.name}##{name}() is not implemented."
raise NotImplementedError.new(mesg)
end
END
module_eval s
end
end
class Foo
abstract_method :m1, :m2, :m3 # define abstract methods
end
obj = Foo.new
obj.m1 #=> Foo#m1() is not implemented yet. (NotImplementedError)
----------
But this solution doesn't allow us to define a method with arguments.
The following is another solution to define abstract method
which is able to define a method with arguments.
? example.rb
----------
module Abstract # or Module?
def not_implemented # or should_be_implemented?
backtrace = caller()
method_name = (backtrace.shift =~ /`(\w+)'$/) && $1
mesg = "#{self.class.name}##{method_name}() is not implemented."
err = NotImplementedError.new(mesg)
err.set_backtrace(backtrace)
raise err
end
end
class Foo
include Abstract
def m1(arg)
not_implemented
end
end
obj = Foo.new
p obj.m1('abc') #=> example.rb:20: Foo#m1() is not implemented.
(NotImplementedError)