I will ask it on a specific example (in Rails). In the “Destroy without Javascript (revised)” railscast, Ryan Bates overwrites the #resources routing method:
module DeleteResourceRoute
def resources(*args, &block)
super(*args) do
# some code
end
end
end
ActionDispatch::Routing::Mapper.send(:include, DeleteResourceRoute)
But doesn’t inheritance in Ruby work in a way that the module is the “superclass”. How can he be calling #super from the module, then?
If it was possible to overwrite a method like this, then people instead of doing this:
class SomeClass
alias old_method method
def method
# ...
old_method
# ...
end
end
could be doing something this:
class SomeClass
include Module.new {
def method
# ...
super
# ...
end
}
end
What am I missing?
I figured it out. There is a module that is included into
ActionDispatch::Routing::Mapper, and that module holds the#resourcesmethod. If#resourceswas defined directly onActionDispatch::Routing::Mapper, and not in the module, overwriting it wouldn’t work in this way (we would have to use the “alias” method instead).About modules and classes in general, the module acts like a superclass to the class that included it. By “acting like a superclass” I mean that, if you have a method
#foodefined on the module, and you include that module into a class, that class can overwrite the#foomethod, and call#super, and that will call the module’s#foomethod. An example: