# frozen_string_literal: true module JsonApiToolbox module Renderizable def render_object(object, options = {}) if object.respond_to?(:errors) && object.errors.any? render(build_error_options(object, options)) else renderization = { jsonapi: object, include: includes_params, fields: fields }.merge(options) render(build_meta_data(object).merge(renderization)) end end def includes_params params.fetch(:includes, {}) end def fields return {} unless fields? params[:fields].permit!.to_h.transform_values do |attributes| attributes.split(',') end end def permitted_params model = controller_name.singularize parsed_params = params.require(model).permit(permitted_attributes).to_h JsonApiToolbox::Postable.normalize_post(parsed_params, model_name) end def default_includes_params model_relationships = model_name.reflect_on_all_associations(:has_one).map(&:name) model_relationships += model_name.reflect_on_all_associations(:has_many).map(&:name) # This line exists to exclude from default_includes_params a relationship # with 'versions' (see gem paper_trail) model_relationships.delete(:versions) params.merge!(includes: model_relationships) end def jsonapi_class version_hash = { 'PaperTrail::Version': JsonApiToolbox::Serializables:: SerializableVersion } Hash.new { |h, k| h[k] = "Serializable#{k}".safe_constantize }. merge(version_hash) end private def fields? params[:fields].present? && params[:fields].respond_to?(:permit!) && params[:fields].permit!.to_h.respond_to?(:map) end def model_name controller_name.singularize.camelize.constantize end def build_line(title, field, message) { title: title, source: field, detail: message } end def build_meta_data(objects) if objects.respond_to?(:count) { meta: { 'total-count' => objects.count } } else {} end end def build_error_options(object, options) options = options.merge(status: :unprocessable_entity) if options[:status].blank? { jsonapi_errors: object.errors }.merge(options) end end end