module JsonSerializer::JsonResponses
Public Instance Methods
json_error(code, message=nil, metadata={})
click to toggle source
helper for returning failure messages in a common format
# File lib/json_serializer/json_responses.rb, line 47 def json_error code, message=nil, metadata={} render :json => { :error => metadata.merge({ :message => message || t("api.errors.#{code}"), :code => code }), }, status: code end
json_model(status, model, extra_params={})
click to toggle source
a standard way to return models. if they have errors then we return the error message this is a DRY approach to creating and updating and then returning JSON responses
# File lib/json_serializer/json_responses.rb, line 63 def json_model status, model, extra_params={} render json: model.serialize.merge(extra_params), status: status end
json_models(status, models, extra_params={})
click to toggle source
a standard way to return an array of models arrays of models are passed back in a data object, this is so we can add things we may need in the future such as pagination
# File lib/json_serializer/json_responses.rb, line 69 def json_models status, models, extra_params={} render json: models.serialize.merge(extra_params), status: status end
json_response(type, hash = {})
click to toggle source
a nice standard response schema for json
# File lib/json_serializer/json_responses.rb, line 10 def json_response(type, hash = {}) # we require one of these types unless [ :ok, :redirect, :error ].include?(type) raise "Invalid json response type: #{type}" end # To keep the structure consistent, we'll build the json # structure with these default properties. default_json = { :status => type, :html => nil, :notice => nil, :to => nil }.merge(hash) return default_json end
json_success(message, hash = {})
click to toggle source
helper for success messages (for actions like delete which dont return models)
# File lib/json_serializer/json_responses.rb, line 38 def json_success message, hash = {} json = { :success => true, :message => message }.merge(hash) render :json => json, status: :accepted end
render_json_response(type, hash = {})
click to toggle source
render our standardized json response
# File lib/json_serializer/json_responses.rb, line 28 def render_json_response(type, hash = {}) render :json => json_response(type, hash) end