1日1%成長するブログ

毎日成長するために仕事/プライベートで得た学びをアウトプットするブログです

Rubyのアクセサメソッドを使ってEntityクラスを作ってAPIのレスポンスに使う

class HogePostsEntity
  attr_reader :author, :comments

  def initialize(post)
    @author = post.author
    @comments = post.comments
  end

  def self.collection(posts)
    posts.map { |post| new(post) }
  end
end

こんな感じでシンプルにEntity用のクラスを作れた。

render json: { status: 200, data: HogePostsEntity.collection(posts) }

APIのレスポンスの整形は全てEntityクラスに任せるようにすれば、 責務がハッキリするし、コントローラーがかなりスッキリしていい感じ。