Ruby中如何正确重写Mixin中的类方法?
问题根源
ResourceTransformation模块里的import是类方法(嵌套在class_methods块中),但你在SomeEntity里写的def import是实例方法——两者不属于同一方法范畴,所以调用SomeEntity.import(类方法调用)时,自然会执行模块里的原方法。
正确重写方式
有两种标准写法可以覆盖模块中的类方法:
写法一:沿用class_methods块风格
和模块的定义方式保持一致,在类中用class_methods块定义同名类方法,还能通过super调用模块原逻辑:
class SomeEntity < ApplicationRecord include ResourceTransformation class_methods do def import(resource) puts "in overriden import method!!!" super(resource) # 可选:调用模块中原有的import逻辑 end end end
写法二:直接定义类方法
用self.import的形式直接在类中定义类方法,效果完全相同:
class SomeEntity < ApplicationRecord include ResourceTransformation def self.import(resource) puts "in overriden import method!!!" super(resource) # 可选:调用模块中原有的import逻辑 end end
验证
调用SomeEntity.import(your_resource)时,就会执行你重写后的类方法逻辑了。
内容的提问来源于stack exchange,提问作者Ryan Pierce Williams
相关产品推荐
相关产品推荐

