How does super work with modules?

I will ask him for a specific example (in Rails). In the " Destroy Without Javascript (Revised) " railscast, Ryan Bates rewrites the routing method #resources :

 module DeleteResourceRoute def resources(*args, &block) super(*args) do # some code end end end ActionDispatch::Routing::Mapper.send(:include, DeleteResourceRoute) 

But non-inheritance in Ruby works in such a way that the module is a "superclass". How can it call #super from a module, then?

If one could rewrite such a method, people instead would instead:

 class SomeClass alias old_method method def method # ... old_method # ... end end 

could do something:

 class SomeClass include Module.new { def method # ... super # ... end } end 

What am I missing?

+4
source share
2 answers

I get it. There is a module that is included in ActionDispatch::Routing::Mapper , and this module supports the #resources method. If #resources was defined directly on ActionDispatch::Routing::Mapper , and not in the module, rewriting it would not work that way (we would have to use the "alias" method).

About modules and classes in general, a module acts as a superclass for the class that included it. By acting as a superclass, I mean that if you have the #foo method defined in the module and you include this module in the class, this class can overwrite the #foo method and call #super , which will call the module method #foo . Example:

 module Foo def foo puts "foo" end end class Bar include Foo def foo super puts "bar" end end Bar.new.foo # foo # bar # => nil 
+1
source

"super" lives only in the "class". super could not live in the context of a "clean module." so when you saw code like:

 module DeleteResourceRoute def resources(*args, &block) super(*args) do # some code end end end 

you must have a class to "enable this module", then "super" takes effect, for example.

 class SomeClass extends BaseClass include DeleteResourceRoute end class BaseClass def resources puts "called parent!" end end SomeClass.new.resources # => called parent! 
+4
source

Source: https://habr.com/ru/post/1439704/


All Articles