Using define_method inside a module that is part of a class?

I have something like this:

module MyModule define_method(:foo){ puts "yeah!" } end class User include MyModule end 

But this does not work as intended ... They are not defined. I also need to use a module because I want to distinguish methods from there from ordinary user methods. What I like:

 MyModule.instance_methods 

Please help .. what am I missing? I also tried:

 module MyModule (class << self; self; end).class_eval do define_method(:foo){ puts "yeah!" } end end 

which also does not work: /

to clarify ... I would like to use:

 User.first.foo 

not

 MyModule.foo 
+6
source share
2 answers

You can always use extend self trick:

 module MyModule define_method(:foo){ puts "yeah!" } extend self end 

This makes it possible to make this module both mixin and singleton.

+8
source

If you want to have a class method, then it will work

 module MyModule define_singleton_method(:foo){ puts "yeah!" } end MyModule.foo # >> yeah! 
+7
source

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


All Articles