I have a Rails app with several models with the same structure:
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
The actual code is more complicated but that's enough for simplicity.
I think I can put the common part of the code in one place and then use it in all models.
Here is what comes to my mind:
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
Obviously it doesn't work for two reasons:
CommonItem
has no idea about class methods I invoke.WIDTH
andHEIGHT
constants are looked up inCommonItem
instead ofItem1
.
I tried to use include
instead of extend
, some ways of class_eval
and class inheritance, but none work.
It seems I am missing something obvious. Please tell me what.
In Ruby, the construct to use to extract repeated code into a single unit is a method:
Here's how I would do it:
The
included
method is called on a module when it's included.I think I've managed to create a similar structure that your problem has. The module is calling the method inherited by the items classes from
Model
class.Output: