Created
November 1, 2012 13:44
-
-
Save teamon/3993700 to your computer and use it in GitHub Desktop.
DRY acts_as_api + custom rails responders integration
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
# config/initilizers/acts_as_api.rb | |
ActsAsApi::Config.include_root_in_json_collections = false |
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
class ApiResponder < ActionController::Responder | |
def to_json | |
render :json => resource.as_api_response(options[:api_template] || :default) | |
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
class Post < ActiveRecord::Base | |
acts_as_api | |
api_accessible :default do |t| | |
t.add :title | |
t.add :content | |
end | |
api_accessible :short do |t| | |
t.add :title | |
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
class PostsController < ApplicationController | |
respond_to :json | |
self.responder = ApiResponder | |
def index | |
@posts = Post.all | |
respond_with(@posts, :api_template => :short) | |
end | |
def show | |
@post = Post.find(params[:id]) | |
respond_with(@post) | |
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
GET /posts.json | |
=> | |
[ | |
{"title": "..."}, | |
{"title", "..."} | |
] | |
GET /posts/1.json | |
=> | |
{ | |
"title": "...", | |
"content": "..." | |
} |
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
# config/initializers/wrap_parameters.rb | |
ActiveSupport.on_load(:active_record) do | |
self.include_root_in_json = false | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment