我有一個Rails應用程序與幾個車型具有相同的結構:擴展Ruby類有一個獨立的代碼
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
和HEIGHT
常數在CommonItem
而不是Item1
中查找。
我試圖用include
代替extend
,class_eval
和類繼承的一些方法,但沒有工作。
看來我失去了一些明顯的東西。請告訴我什麼。
http://api.rubyonrails.org/類/ ActiveSupport/Concern.html是爲這樣的東西。 – jdoe