DonutWorks / Ari

0 stars 0 forks source link

서비스 오브젝트 활용하기 #331

Open shaynekang opened 9 years ago

shaynekang commented 9 years ago

서비스 오브젝트라는 개념이 있습니다. 제가 자주 링크하는 7 Patterns to Refactor Fat ActiveRecord Models에도 나와있는데요, 여러개의 모델을 동시에 고쳐야 하는 복잡한 로직이 있을 경우, 서비스 오브젝트를 활용하면 코드가 간결해집니다.

특히나 모델 내부에 존재하는 코드 중, 두 개 이상의 모델을 건드리는 코드는 서비스 오브젝트로 빼는 걸 추천합니다. 가령

class Notice < ActiveRecord::Base
  before_save :change_candidates_status, if: :to_notice?

private
  def change_candidates_status
    candidates_count = to - go_responses.count
    candidates = wait_responses.order(created_at: :asc).limit(candidates_count)
    candidates.update_all(status: "go")
  end
end

다음의 코드는 Notice 모델 외에도 Response 모델을 건드리게 되는데, 이러한 코드는 Notice 모델에 있는 것 보다 서비스 오브젝트로 빼는 게 더 좋습니다. 다른 코드에도 비슷한 경우가 있다면 수정하면 좋겠습니다. ㅎㅎ