Class: RestfulJSONP::JSONPResponder

Inherits:
ActionController::Responder
  • Object
show all
Defined in:
lib/restful_jsonp/jsonp_responder.rb

Instance Method Summary collapse

Instance Method Details

#display(resource, given_options = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/restful_jsonp/jsonp_responder.rb', line 6

def display(resource, given_options = {})
  if format == :json && controller.params[:callback] && !controller.request.xhr?
    # this is a JSONP request (note that JSONP is not done over XHR!)

    jsonp_options = {}
    
    status = given_options[:status] || options[:status]

    if (resource.respond_to?(:errors) && !resource.errors.empty?) ||
        (status && ![:ok, :created].include?(status))
      jsonp_options[:status] = :accepted # we can't return an error HTTP response (e.g. 422 or 500) because it would be ignored :(
      resource = {
        :error => {
          :status => status,
          :data => resource.to_json
        }
      }
    end

    jsonp_options[format] = resource
    jsonp_options[:callback] = controller.params[:callback]

    render options.merge!(given_options).merge!(jsonp_options)
  else
    # this is not a JSONP request; carry on
    super
  end
end