I’m working on an interesting problem. I have a Products
model containing a description
, price
, and sku
and so forth. It’s meant to be used in conjunction with another Package
model, which itself will have description
, price
, and sku
. I would like to have my Package
model delegate these fields to it’s parent Package
if these fields are nil/blank/zero, otherwise I want it to assume normal behavior. Essentially I want my Product
definition to behave as a template for these fields when they’re not set. I should note that Product
also defines some logic and houses data that is shared amongst it’s Package
children, so unfortunately I can’t completely eliminate it from the equation.
I tried using delegate, a la:
class Package < ActiveRecord::Base
belongs_to :product
delegate :description, :sku, :price, to: :product
end
Which seems to delegate properly, however this makes it impossible to retrieved assigned values once delegated. I also tried define_method
only to meet similar results:
class Package < ActiveRecord::Base
belongs_to :product
def initialize(*attr)
super(*attr)
[:description, :sku, :price].each do |attr|
if send(attr).nil?
self.class.instance_eval do
define_method(attr) do
product.try(attr)
end
end
end
end
end
end
It occurs to me that I can simply write a callback method to set the fields if they’re blank/nil/zero, but I was curious if somebody could think of a more elegant approach or better design alltogether.