module RenderJsonRails::Helper

Public Class Methods

find_render_json_options_class!(object) click to toggle source
# File lib/render_json_rails/helper.rb, line 46
def self.find_render_json_options_class!(object)
  return nil if object == nil

  if object.class.respond_to?(:render_json_options)
    object.class
  # elsif object.is_a?(ActiveRecord::Base)
  #   raise "klasa: #{object.class} nie ma konfiguracji 'render_json_config'"
  elsif object.respond_to?(:first)
    RenderJsonRails::Helper.find_render_json_options_class!(object[0])
  else
    nil
  end

end

Public Instance Methods

render_json(object, override_render_json_config: nil, additional_config: nil, status: nil, location: nil) click to toggle source

xxx.yyyy.test/object.json?formatted=yes&fields[invoice]=number,sales_code&fields[invoice_position]=price_gross&include=positions parametry: formatted=yes& fields=number,sales_code fields=price_gross include=positions

# File lib/render_json_rails/helper.rb, line 20
def render_json(object, override_render_json_config: nil, additional_config: nil, status: nil, location: nil)

  if (class_object = RenderJsonRails::Helper.find_render_json_options_class!(object))
    includes = params[:include].to_s.split(',').map { |el| el.to_s.strip } if params[:include]
    options = class_object.render_json_options(
      includes: includes,
      fields: params[:fields],
      override_render_json_config: override_render_json_config,
      additional_config: additional_config,
      additional_fields: params[:additional_fields]
    )
  else
    options = {}
  end

  if params[:formatted] && !Rails.env.development? || params[:formatted] != 'no' && Rails.env.development?
    json = JSON.pretty_generate(object.as_json(options))
    render json: json, status: status, location: location
  else
    options[:json] = object
    options[:status] = status
    options[:location] = location
    render options
  end
end