Sha256: 47d14e6fa61898ba52615938604b316a15a6612207190a77fbdc5194d2ffe3fe

Contents?: true

Size: 1.19 KB

Versions: 14

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

require 'json'

require 'pi_resources/serializer/base'

module PiResources
  module Serializer
    class HashSerializer
      include Base

      attr_reader :hash, :meta, :message, :root

      def initialize(resource, meta: nil, message: nil, context: nil, root: true)
        @hash     = resource
        @resource = resource
        @meta     = meta
        @message  = message
        @context  = context || {}
        @root     = root
      end

      def data
        hash
      end

      protected

      def serializable_hash!
        if root
          result = {}

          result[run_key_transform!(:data)]    = serialize_data
          result[run_key_transform!(:meta)]    = meta&.deep_transform_keys { |key| run_key_transform!(key) } if meta
          result[run_key_transform!(:message)] = message if message

          result
        else
          serialize_data
        end
      end

      def serialize_data
        if self.class.collection? @resource
          @resource.map { |o| o.deep_transform_keys { |key| run_key_transform!(key) } }
        else
          @resource&.deep_transform_keys { |key| run_key_transform!(key) }
        end
      end
    end
  end
end

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
pi-resources-rails-0.6.3 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.6.2 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.6.1 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.6.0 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.5.0 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.4.4 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.4.3 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.4.2 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.4.1 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.4.0 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.3.0 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.2.0 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.1.1 lib/pi_resources/serializer/hash_serializer.rb
pi-resources-rails-0.1.0 lib/pi_resources/serializer/hash_serializer.rb