2011-05-31 4 views
0

私はこれらの非常によく似たクラスがあります。私も、私はそれが親に抽出することができて貼り付けていなかったいくつかのメソッドを持っているRuby/Railsの親クラスと同様の検証/関係をどのように抽象化しますか?

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 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 

とします。私は親のクラス名を知る必要があります。私はこれを行うと:self.to_sCommercialDocumentあるので

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 

は、それは、動作しません。

親クラスでこの動作をどのようにリファクタリングしますか? 私は物事をモジュールに入れてインポ​​ートすることができますが、文書の階層全体はほとんど役に立たなくなります。 私は既にドキュメントの階層を持っていますので、できれば、方法があればそれを使いたいと思います。

答えて

0

あなたは私がClass.inheritedを使用傾けると思いますClass.inherited

+0

を使用して試みることができます。これは、すべての子コードが完全に評価された後に呼び出されます。私はリファクタリングすることができないいくつかの方法がありますが、彼らは仕事に関係が必要です。 –

+0

私はなぜそれがうまくいかないのかわかりません。継承したメソッドで 'subclass.send:has_many、:"#{subclass.to_s.underscore} _lines "のようなものを試しましたか? – Ian