比方說,我有一個帳戶類和一個AccountReport類。在帳戶#顯示我想顯示一個帳戶的報告。 Account和AccountReport都有一些公開的方法。以下哪種技術更好?委託或實例化額外的類?
1)實例化一個賬戶和一個賬戶報告,用賬戶數據初始化賬戶報告。
class AccountsController < ActionController::Base
def show
@account = current_user.account
@account_report = AccountReport.new(@account.orders)
respond_with(@account)
end
# ...
end
2)允許帳戶的實例來實例化AccountReport和委託方法調用
class Account < ActiveRecord::Base
attr_reader :account_report
delegate :method_a, :method_b, :method_c, :method_d, :to => :account_report
after_initialize :setup_account_report
def setup_account_report
@account_report = AccountReport.new(orders)
end
# ...
end
選項2似乎是一個更簡潔的方法給我,但有很多的方法加載了帳戶使得它感覺像一個上帝階級。
我想我明白了。我喜歡懶惰地加載報告的想法。是否有可能以這種方式委託給AccountReport/Report,或者是否需要使用方法鏈接account.report.total,並使用此方法? –
'@report || = AccountReport.new(self.orders)'是你上面試圖做的一個很好的比喻。 –
謝謝!我已經將這兩條建議結合起來,它的運作非常好。我甩掉了我的讀者,寫了一個獲取報告的方法,然後在那裏返回或初始化它。 –