Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prepend classmethods

Tags:

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?

like image 203
Sören Titze Avatar asked Sep 08 '13 12:09

Sören Titze


People also ask

What is the difference between extend and include in Ruby?

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.

How do I add a module in Rails?

You can include a module in a class in your Rails project by using the include keyword followed by the name of your module.

How do I import a module into Ruby?

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.


1 Answers

A simpler version:

module Extensions   def bar     'Extended Bar!'   end   end  Foo.singleton_class.prepend Extensions 
like image 80
Alex Davis Avatar answered Nov 06 '22 13:11

Alex Davis