lib/ballast/concerns/ajax.rb in ballast-1.5.1 vs lib/ballast/concerns/ajax.rb in ballast-1.5.2
- old
+ new
@@ -32,21 +32,22 @@
# Sends an AJAX response to the client.
#
# @param data [Hash] The response to send.
# @param status [Symbol|Fixnum] The HTTP status of the response, *ignored if already set in data*.
# @param format [Symbol] The content type of the response.
- def send_ajax(data, status: :ok, format: :json)
+ # @param pretty_json [Boolean] If JSON response must be pretty formatted.
+ def send_ajax(data, status: :ok, format: :json, pretty_json: false)
if !performed? then
# Prepare data
data = prepare_ajax_send(data, status)
# Setup callback and format
format, callback, content_type = format_ajax_send(format)
status = data[:status]
- # Prepare data for formatting
- data = ActiveSupport::JSON.encode(data) if [:json, :jsonp, :pretty_json, :pretty_jsonp, :text].include?(format)
+ # Adjust data
+ data = (pretty_json ? Oj.dump(data) : ActiveSupport::JSON.encode(data)) if [:json, :jsonp, :text].include?(format)
# Render
render(format => data, status: status, callback: callback, content_type: content_type)
end
end
@@ -102,12 +103,11 @@
# Sets up parameters to send a response.
#
# @param format [Symbol] The format of the data.
# @return [Array] An array of format, callback and content_type.
def format_ajax_send(format)
- format ||= params[:format] || request.format || "json"
- format = format.to_sym
- callback = format == :jsonp ? (params[:callback] || "jsonp#{Time.now.to_i}") : nil
+ format = (format || params[:format] || request.format || "json").to_sym
+ callback = [:jsonp, :pretty_jsonp].include?(format) ? (params[:callback] || "jsonp#{Time.now.to_i}") : nil
content_type = (format == :text) ? "text/plain" : nil
[format, callback, content_type]
end
end
\ No newline at end of file