계정 클래스와 AccountReport 클래스가 있다고 가정 해 보겠습니다. accounts # show 계정에 대한 보고서를 보여주고 싶습니다. Account와 AccountReport는 여러 가지 public 메소드를 가지고 있습니다. 뒤에 오는 기술의 어느 기술이 더 낫습니까?추가 클래스를 위임하거나 인스턴스화 하시겠습니까?
1) 계정 및 AccountReport를 인스턴스화하고 계정 데이터로 AccountReport를 초기화합니다.
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
호출 인스턴스화 할 수 있도록 허용 하나님 계급.
나는 그것을 얻는다 고 생각한다. 나는 보고서를 느리게로드한다는 생각을 좋아합니다. 이런 식으로 AccountReport/Report에 위임 할 수 있습니까? 아니면이 방법으로 account.report.total 메서드 체인을 사용해야합니까? –
'@report || = AccountReport.new (self.orders)'는 위에서 뭘 하려는지에 대한 훌륭한 은유입니다. –
감사합니다. 나는이 두 가지 조언을 결합하여 아름답게 작동하고 있습니다. 나는 독자를 버렸고, 보고서를 얻고 그곳에서 보고서를 반환하거나 초기화하는 방법을 썼다. –