class Ballast::AjaxResponse

An AJAX response.

@attribute status

@return [Symbol|Fixnum] The HTTP status of the response.

@attribute data

@return [Object|Hash|NilClass] The data to send to the client.

@attribute error

@return [Object|NilClass] A error message.

@attribute transport

@return [Object|NilClass] The transport to use for sending. Must respond to `render`, `params`, `request.format` and `performed?`.

Attributes

data[RW]
error[RW]
status[RW]
transport[RW]

Public Class Methods

new(status: :ok, data: {}, error: nil, transport: nil) click to toggle source

Creates an AJAX response.

@param status [Symbol|Fixnum] The HTTP status of the response. @param data [Object|Hash|NilClass] Additional data to append to the response. @param error [Object|NilClass] A error to append to the response. @param transport [Object|NilClass] The transport to use for sending. Must respond to `render`, `params`, `request.format` and `performed?`.

# File lib/ballast/ajax_response.rb, line 26
def initialize(status: :ok, data: {}, error: nil, transport: nil)
  @status = status
  @data = data
  @error = error
  @transport = transport
end

Public Instance Methods

as_json(options = {}) click to toggle source

Returns a JSON representation of the response.

@param options [Hash] The options to use for serializing. Currently only `original_status` is supported. @return [Hash] A JSON representation of the response.

# File lib/ballast/ajax_response.rb, line 44
def as_json(options = {})
  {
    status: options[:original_status] ? status : numeric_status,
    data: data,
    error: error
  }
end
numeric_status() click to toggle source

Returns the status as a number.

@return [Fixnum] The status as a number.

# File lib/ballast/ajax_response.rb, line 36
def numeric_status
  status.is_a?(Fixnum) ? status : Rack::Utils.status_code(status.ensure_string.to_sym)
end
reply(format: :json, pretty_json: false) click to toggle source

Sends the response using the transport.

@param format [Symbol] The content type of the response. @param pretty_json [Boolean] If JSON response must be pretty formatted.

# File lib/ballast/ajax_response.rb, line 56
def reply(format: :json, pretty_json: false)
  return if transport.performed?

  format, callback, content_type = format_reply(format)
  content = prepare_content
  content = (pretty_json ? Oj.dump(content) : ActiveSupport::JSON.encode(content)) if [:json, :jsonp, :text].include?(format)

  transport.render(format => content, status: numeric_status, callback: callback, content_type: content_type)
end