Enforce implementation of Module method

P

Paul

Let's say I have the following module:

------------------------
module Parenting

def add_child(a_child)
self.children.push(a_child)
end

def delete_child(a_child)
self.children.delete(a_child)
end

def children
# need to implement
end

end
 
K

Ken Bloom

Let's say I have the following module:

------------------------
module Parenting

def add_child(a_child)
self.children.push(a_child)
end

def delete_child(a_child)
self.children.delete(a_child)
end

def children
# need to implement
end

end
------------------------

Is there a way to enforce that the 'children' method is implemented in
any class which includes this module? Or do I simply rely on a
commenting convention, as above?

It may be the more ruby way to rely on the commenting convention (there's
no need to define the children method at all in Parenting, just comment
somewhere that it needs to be implemented.)

But if checking is really a must, then you can check from
Parenting.included as follows:

module Parenting
def self.included klass
raise NoMethodError, "#{klass} must define #children" unless
klass.method_defined? :children
end
end
 
P

Phrogz

Let's say I have the following module:

------------------------
module Parenting

def add_child(a_child)
self.children.push(a_child)
end

def delete_child(a_child)
self.children.delete(a_child)
end

def children
# need to implement
end

end
------------------------

Is there a way to enforce that the 'children' method is implemented in
any class which includes this module? Or do I simply rely on a
commenting convention, as above?

module Parenting
def children
raise "OOPS!" #Better error message here
end
end

If a class defines that method, it will shadow the module method. As
long as the class method doesn't try to call super, you should be good
to go.
 
G

Gareth Adams

Phrogz said:
module Parenting
def children
raise "OOPS!" #Better error message here
end
end

If a class defines that method, it will shadow the module method. As
long as the class method doesn't try to call super, you should be good
to go.

And of course, there's a rather handy NotImplementedError class just sat there
in Ruby code if you want to use it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top