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クラスに任せるようにすれば、 責務がハッキリするし、コントローラーがかなりスッキリしていい感じ。