[英]How to call a method with dynamic dispatch (when method is part of a Module), in Ruby?
[英]Ruby how to call method from prepended module
我有一個模型:
class MyModel
prepend MyModelOverride
def find_something
#returns something
end
end
module MyModelOverride
included do
def method1
find_something
end
end
end
MyModel.new.method1
最后一次調用返回以下錯誤:
NoMethodError: undefined method `method1' for #<MyModel:0x007f089c673b48>
如何正確格式化MyModelOverride中的代碼,以便可以從MyModel實例中調用其中的方法, 並可以從其中調用MyModel的其他方法?
要通過mixin /模塊包含方法,您需要做的是:
module MyModelOverride
def method1
find_something
end
end
這將使method1
成為您將其包含到的任何類的實例方法。
您在示例中使用的included
塊來自ActiveSupport :: Concern 。 如果要使用ActiveSupport :: Concern獲得更高級的包含概念,只需將其包含在模塊中:
module MyModelOverride
extend ActiveSupport::Concern
included do
# macros to run when module is included, like `scope` or `has_many` etc.
end
def method1
find_something
end
end
我會使用prepended
鈎子:-
module MyModelOverride
def self.prepended(klass)
klass.class_eval do
def method1
find_something
end
end
end
end
class MyModel
prepend MyModelOverride
def find_something
12
end
end
MyModel.new.method1 # => 12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.