0

我有这些非常相似的课程:

class DeliveryDocument < CommercialDocument
  # Relations
  belongs_to :biller, :class_name => 'Company'
  belongs_to :customer, :class_name => 'Company'
  belongs_to :customer_center, :class_name => 'Center'
  has_many :delivery_document_lines, :dependent => :destroy
  alias_attribute :lines, :delivery_document_lines
  # Some configuration
  accepts_nested_attributes_for :delivery_document_lines
  acts_as_freezable :only_dependencies => true,
    :has_many => [:delivery_document_lines],
    :belongs_to => [:biller, :customer, :customer_center]
  acts_as_clonable :has_many => [:delivery_document_lines]
  validates_each :lines do |record, attr, value|
    # ...
  end
end

和:

class InvoiceDocument < CommercialDocument
  self.
  # Relations
  belongs_to :biller, :class_name => 'Company'
  belongs_to :customer, :class_name => 'Company'
  belongs_to :customer_center, :class_name => 'Center'
  has_many :invoice_document_lines, :dependent => :destroy
  alias_attribute :lines, :invoice_document_lines
  # Some configuration
  accepts_nested_attributes_for :invoice_document_lines
  acts_as_freezable :only_dependencies => true,
    :has_many => [:invoice_document_lines],
    :belongs_to => [:biller, :customer, :customer_center]
  acts_as_clonable :has_many => [:invoice_document_lines]
  # Validations
  validates_each :lines do |record, attr, value|
    # ...
  end
end

我也有一些我没有粘贴的方法可以提取到父级。我只需要知道父类中的类名。当我这样做时:

class CommercialDocument < Document  # document inherits from AR::Base
  # ...
  has_many :"#{self.to_s.underscore}_lines", :dependent => :destroy
  # ...
  accepts_nested_attributes_for :"#{self.to_s.underscore}_lines"
  # ...
end

self.to_s它不起作用,因为CommercialDocument.

您将如何在父类中重构这种行为?我可以将东西放在一个模块中并导入它,但是整个文档层次结构几乎变得毫无用处。我已经有了文档的层次结构,所以如果可以的话,如果有办法,我想使用它。

4

1 回答 1

0

您可以尝试使用Class.inherited

于 2011-05-31T20:39:08.017 回答