Created
May 3, 2011 18:51
-
-
Save cookrn/953958 to your computer and use it in GitHub Desktop.
Presenters As A Solution To as_json Woes In Rails APIs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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