Sha256: d66962f9810d211389e88ae74150532d93e93a38b953f12433bb699127e8168a

Contents?: true

Size: 1.03 KB

Versions: 6

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

class Serega
  class ConvertItem
    module ConvertItemClassMethods
      def call(object, context, map)
        return unless object

        map.each_with_object({}) do |(attribute, nested_attributes), hash|
          value = attribute.value(object, context)
          attach_value(value, hash, attribute, nested_attributes, context)
        end
      end

      private

      def attach_value(value, hash, attribute, nested_attributes, context)
        hash[attribute.name] =
          if nested_attributes.empty?
            attribute.relation? ? FROZEN_EMPTY_HASH : value
          elsif many?(attribute, value)
            value.map { |val| call(val, context, nested_attributes) }
          else
            call(value, context, nested_attributes)
          end
      end

      def many?(attribute, object)
        is_many = attribute.many
        is_many.nil? ? object.is_a?(Enumerable) : is_many
      end
    end

    extend Serega::Helpers::SerializerClassHelper
    extend ConvertItemClassMethods
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
serega-0.1.5 lib/serega/convert_item.rb
serega-0.1.4 lib/serega/convert_item.rb
serega-0.1.3 lib/serega/convert_item.rb
serega-0.1.2 lib/serega/convert_item.rb
serega-0.1.1 lib/serega/convert_item.rb
serega-0.1.0 lib/serega/convert_item.rb