Sha256: e2154dbcd5b697f27b654968d2639825c2ba6ac6aa6bbfc646f6e00da79afc1c

Contents?: true

Size: 1.88 KB

Versions: 4

Compression:

Stored size: 1.88 KB

Contents

module PowerApi
  module ApplicationHelper
    VALID_SERIALIZER_OUTPUT_FORMATS = %i{json hash}

    def serialize_resource(resource, options = {})
      load_default_serializer_options(options)
      serializable = ActiveModelSerializers::SerializableResource.new(resource, options)
      serialized_data = serializable.serializable_hash
      render_serialized_data(serialized_data, options)
    rescue NoMethodError => e
      if e.message.include?("undefined method `serializable_hash'")
        raise ::PowerApi::InvalidSerializableResource.new(
          "Invalid #{resource.class} resource given. Must be ActiveRecord instance or collection"
        )
      else
        raise e
      end
    end

    private

    def render_serialized_data(serialized_data, options)
      output_format = options.delete(:output_format)
      serialized_data = serialized_data[:root] if options[:root] == :root
      return serialized_data if output_format == :hash

      serialized_data.to_json
    end

    def load_default_serializer_options(options)
      options[:namespace] ||= "Api::Internal"
      options[:key_transform] ||= :camel_lower
      options[:include_root] ||= false
      options[:output_format] = format_serializer_output_format!(options[:output_format])
      options[:key_transform] = :unaltered if options[:output_format] == :hash

      load_root_option(options)
      options
    end

    def load_root_option(options)
      return if !!options.delete(:include_root)

      options[:root] = :root
    end

    def format_serializer_output_format!(output_format)
      return :json if output_format.blank?

      output_format = output_format.to_s.to_sym

      if !VALID_SERIALIZER_OUTPUT_FORMATS.include?(output_format)
        raise ::PowerApi::InvalidSerializerOutputFormat.new(
          "Only #{VALID_SERIALIZER_OUTPUT_FORMATS} values are allowed."
        )
      end

      output_format
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
power_api-2.1.0 app/helpers/power_api/application_helper.rb
power_api-2.0.2 app/helpers/power_api/application_helper.rb
power_api-2.0.1 app/helpers/power_api/application_helper.rb
power_api-2.0.0 app/helpers/power_api/application_helper.rb