I got 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. Also I need to use the Module because I want to distinguish the Methods from there from the normal User Methods. Which I do like this:
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 doesn't work :/
to clarify ... I would like to use:
User.first.foo
not
MyModule.foo
You can always use the extend self
trick:
module MyModule
define_method(:foo){ puts "yeah!" }
extend self
end
This has the effect of making this module both a mixin and a singleton.
If you want to have a class method the following will work
module MyModule
define_singleton_method(:foo){ puts "yeah!" }
end
MyModule.foo
# >> yeah!
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