Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Presenters As A Solution To as_json Woes In Rails APIs
# app/presenters/api/v1/other_resource_presenter.rb
class Api::V1::OtherResourcePresenter
attr_reader :other_resource
def initialize( other_resource )
@other_resource = other_resource
end
def as_json( include_root = false )
data_hash = {
:attr3 => @other_resource.attr3,
:attr4 => @other_resource.attr4,
:resource => resource
}
data_hash = { :other_resource => data_hash } if include_root
data_hash
end
def resource
Api::V1::ResourcePresenter.new( @other_resource.resource ).as_json( false )
end
end
# app/controllers/api/v1/resource_controller.rb
class Api::V1::ResourceController < Api::V1::BaseController
def show
@resource = Resource.find_by_id( params[:id] )
render :status => 404 unless @resource
@resource_presenter = Api::V1::ResourcePresenter.new( @resource ).as_json
render :json => @resource_presenter
end
end
# app/presenters/api/v1/resource_presenter.rb
class Api::V1::ResourcePresenter
attr_reader :resource
def initialize( resource )
@resource = resource
end
def as_json( include_root = false )
data_hash = {
:attr1 => @resource.attr1,
:attr2 => @resource.attr2
}
data_hash = { :resource => data_hash } if include_root
data_hash
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment