Sha256: 3fd7d8bd8e43be5ebb2cffd7b667a38882f05b526764fbcd774c547697b6879d

Contents?: true

Size: 775 Bytes

Versions: 6

Compression:

Stored size: 775 Bytes

Contents

# frozen_string_literal: true

module Strict
  module Attributes
    class Coercer
      attr_reader :attributes_class

      def initialize(attributes_class)
        @attributes_class = attributes_class
      end

      def call(value)
        return value if value.nil? || !value.respond_to?(:to_h)

        coerce(value.to_h)
      end

      private

      NOT_PROVIDED = ::Object.new.freeze

      def coerce(hash)
        attributes_class.new(
          **attributes_class.strict_attributes.each_with_object({}) do |attribute, attributes|
            value = hash.fetch(attribute.name) { hash.fetch(attribute.name.to_s, NOT_PROVIDED) }
            attributes[attribute.name] = value unless value.equal?(NOT_PROVIDED)
          end
        )
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
strict-1.5.0 lib/strict/attributes/coercer.rb
strict-1.4.0 lib/strict/attributes/coercer.rb
strict-1.3.1 lib/strict/attributes/coercer.rb
strict-1.3.0 lib/strict/attributes/coercer.rb
strict-1.2.0 lib/strict/attributes/coercer.rb
strict-1.1.0 lib/strict/attributes/coercer.rb