[英]Using define_method inside a Module that gets included inside a Class?
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
If you want to have a class method the following will work 如果您想要一个类方法,以下方法将起作用
module MyModule
define_singleton_method(:foo){ puts "yeah!" }
end
MyModule.foo
# >> yeah!
You can always use the extend self
trick: 你总是可以使用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. 这具有使该模块既是mixin又是singleton的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.