使用独立代码扩展Ruby类
我有一个Rails应用程序,其中包含几个具有相同结构的模型:
class Item1 true end class Item2 true end
实际代码更复杂,但这足以简化。
我想我可以将代码的公共部分放在一个地方,然后在所有模型中使用它。
以下是我的想法:
class Item1 true end
显然它不起作用有两个原因:
-
CommonItem
不知道我调用的类方法。 - 在
CommonItem
而不是Item1
中查找WIDTH
和HEIGHT
常量。
我尝试使用include
而不是extend
, class_eval
和类inheritance的某些方法,但没有一个工作。
我似乎错过了一些明显的东西。 请告诉我什么。
这是我将如何做到这一点:
class Model def self.model_method puts "model_method" end end module Item def self.included(base) base.class_eval do p base::WIDTH, base::HEIGHT model_method end end end class Item1 < Model WIDTH = 100 HEIGHT = 100 include Item end class Item2 < Model WIDTH = 200 HEIGHT = 200 include Item end
included
方法在模块上调用时调用。
我想我已经设法创建了一个与你的问题相似的结构。 该模块正在调用Model
类中的items类inheritance的方法。
输出:
100 100 model_method 200 200 model_method
在Ruby中,用于将重复代码提取到单个单元中的构造是一种方法 :
class Model def self.model_method p __method__ end private def self.item p self::WIDTH, self::HEIGHT model_method end end class Item1 < Model WIDTH = 100 HEIGHT = 100 item end class Item2 < Model WIDTH = 200 HEIGHT = 200 item end