Skip to content

Instantly share code, notes, and snippets.

@teamon
Created November 1, 2012 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teamon/3993700 to your computer and use it in GitHub Desktop.
Save teamon/3993700 to your computer and use it in GitHub Desktop.
DRY acts_as_api + custom rails responders integration
# config/initilizers/acts_as_api.rb
ActsAsApi::Config.include_root_in_json_collections = false
class ApiResponder < ActionController::Responder
def to_json
render :json => resource.as_api_response(options[:api_template] || :default)
end
end
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
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
GET /posts.json
=>
[
{"title": "..."},
{"title", "..."}
]
GET /posts/1.json
=>
{
"title": "...",
"content": "..."
}
# 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