Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting rails to only responding to JSON and XML requests

Is there a way to globally define a rails app to only serve json and xml and appropriately error on any other requests?

I'm thinking it's something along the lines of a before_filter and responds_to block in the ApplicationController but that's as far as my investigation has got me.

like image 771
Nick Avatar asked Jan 16 '12 19:01

Nick


2 Answers

Just declare it at the class level on your controller, using respond_to. It will apply to all your controllers if you do it on ApplicationController

class ApplicationController < ActionController::Base
  respond_to :xml, :json
  …
end

Also read about ActionController::Responder class for more options.

like image 197
edgerunner Avatar answered Oct 27 '22 03:10

edgerunner


To make json response on errors, just add the following code to your application_controller:

rescue_from Exception, :with => :render_error
rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found
rescue_from ActionController::RoutingError, :with => :render_not_found
rescue_from ActionController::UnknownController, :with => :render_not_found
rescue_from ActionController::UnknownAction, :with => :render_not_found

private

def render_not_found(exception)
  # logger.info(exception) # for logging 
  respond_to do |format|
    render json: {:error => "404"}, status: 404
  end    
end

def render_error(exception)
  # logger.info(exception) # for logging
  respond_to do |format|
    render json: {:error => "500"}, status: 500
  end
end

public

def some_public_func
 #do sthg
end
like image 20
mustafaturan Avatar answered Oct 27 '22 02:10

mustafaturan