This question directly relates to this one. But I tried to break it down to the base problem and I didn't want to enter even more text into the other question box. So here goes:
I know that I can include classmethods by extending the module ClassMethods and including it via the Module#include hook. But can I do the same with prepend? Here is my example:
class Foo:
class Foo def self.bar 'Base Bar!' end end
class Extensions:
module Extensions module ClassMethods def bar 'Extended Bar!' end end def self.prepended(base) base.extend(ClassMethods) end end # prepend the extension Foo.send(:prepend, Extensions)
class FooE:
require './Foo' class FooE < Foo end
and a simple startscript:
require 'pry' require './FooE' require './Extensions' puts FooE.bar
When I start the script I don't get Extended Bar!
like I expect but rather Base Bar!
. What do I need to change in order to work properly?
In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.
You can include a module in a class in your Rails project by using the include keyword followed by the name of your module.
include is the most used and the simplest way of importing module code. When calling it in a class definition, Ruby will insert the module into the ancestors chain of the class, just after its superclass.
A simpler version:
module Extensions def bar 'Extended Bar!' end end Foo.singleton_class.prepend Extensions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With