I am working on an API which returns JSON only.
All Exceptions/Errors are caught by an around_filter, and an appropriate JSON response is rendered from there.
Since all I want to return from my actions is a s开发者_JS百科tatus, and all errors are handled by the around_filter, the last line of all my actions now looks like
render :json => {:message => {:status => :ok}}
Is there a way to tell rails to always render that line by default so that I don't have to add it to all my 274628 actions?
Remove all your templates and render statements.
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
rescue_from ActionView::MissingTemplate do |exception|
# This will not work for partials
render :json => {:message => {:status => :ok}}
end
end
# some method in the controller
class PostController < ApplicationController
respond_to :json, :html, :xml
def index
puts "index"
end
end
Personally, I would not do this. If you really have 274,628 actions I would break up your app into smaller services (I know you are joking) :) . I just like being explicit about rendering even if it's more typing. Also overriding defaults makes your app harder to explain and your code less clear.
I personally like the Grape API gem's design of default rendering. You can mount a Grape API inside a rails app. Maybe look at that for a cleaner solution.
精彩评论