我有一个 Rails 应用程序,其中有多个具有相同结构的模型:
class Item1 < ActiveRecord::Base
WIDTH = 100
HEIGHT = 100
has_attached_file :image, styles: {original: "#{WIDTH}x#{HEIGHT}"}
validates_attachment :image, :presence => true
end
class Item2 < ActiveRecord::Base
WIDTH = 200
HEIGHT = 200
has_attached_file :image, styles: {original: "#{WIDTH}x#{HEIGHT}"}
validates_attachment :image, :presence => true
end
实际的代码更复杂,但这已经足够简单了。
我想我可以将代码的公共部分放在一处,然后在所有模型中使用它。
这是我的想法:
class Item1 < ActiveRecord::Base
WIDTH = 100
HEIGHT = 100
extend CommonItem
end
module CommonItem
has_attached_file :image, styles: {original: "#{WIDTH}x#{HEIGHT}"}
validates_attachment :image, :presence => true
end
显然它不起作用有两个原因:
-
CommonItem
不知道我调用的类方法。
-
WIDTH
and HEIGHT
常量在中查找CommonItem
代替Item1
.
我尝试使用include
代替extend
,一些方法class_eval
和类继承,但都不起作用。
看来我错过了一些明显的东西。请告诉我什么。
我会这样做:
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
The included
当包含模块时,会在模块上调用该方法。
我想我已经成功创建了与您的问题类似的结构。该模块正在调用项目类继承的方法Model
class.
Output:
100
100
model_method
200
200
model_method
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)