使用独立代码扩展Ruby类

我有一个Rails应用程序,其中包含几个具有相同结构的模型:

class Item1  true end class Item2  true end 

实际代码更复杂,但这足以简化。

我想我可以将代码的公共部分放在一个地方,然后在所有模型中使用它。

以下是我的想法:

 class Item1  true end 

显然它不起作用有两个原因:

  1. CommonItem不知道我调用的类方法。
  2. CommonItem而不是Item1中查找WIDTHHEIGHT常量。

我尝试使用include而不是extendclass_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