Reputation: 685
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
Upvotes: 7
Views: 3069
Reputation: 211740
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.
Upvotes: 8
Reputation: 14503
If you want to have a class method the following will work
module MyModule
define_singleton_method(:foo){ puts "yeah!" }
end
MyModule.foo
# >> yeah!
Upvotes: 8