Sha256: 1c92900d1f0f4506b16ff9e2423af515e4878340611d2d35f0b47522f0c7945a

Contents?: true

Size: 1.84 KB

Versions: 1

Compression:

Stored size: 1.84 KB

Contents

module Virtus
  class Attribute

    # EmbeddedValue handles virtus-like objects, OpenStruct and Struct
    #
    class EmbeddedValue < Attribute
      TYPES = [Struct, OpenStruct, Virtus, Model::Constructor].freeze

      # Abstract EV coercer class
      #
      # @private
      class Coercer
        attr_reader :primitive

        def initialize(primitive)
          @primitive = primitive
        end

      end # Coercer

      # Builds Struct-like instance with attributes passed to the constructor as
      # a list of args rather than a hash
      #
      # @private
      class FromStruct < Coercer

        # @api public
        def call(input)
          if input.kind_of?(primitive)
            input
          elsif not input.nil?
            primitive.new(*input)
          end
        end

      end # FromStruct

      # Builds OpenStruct-like instance with attributes passed to the constructor
      # as a hash
      #
      # @private
      class FromOpenStruct < Coercer

        # @api public
        def call(input)
          if input.kind_of?(primitive)
            input
          elsif not input.nil?
            primitive.new(input)
          end
        end

      end # FromOpenStruct

      # @api private
      def self.handles?(klass)
        klass.is_a?(Class) && TYPES.any? { |type| klass <= type }
      end

      # @api private
      def self.build_type(definition)
        Axiom::Types::Object.new { primitive definition.primitive }
      end

      # @api private
      def self.build_coercer(type, _options)
        primitive = type.primitive

        if primitive < Virtus || primitive < Model::Constructor || primitive <= OpenStruct
          FromOpenStruct.new(primitive)
        elsif primitive < Struct
          FromStruct.new(primitive)
        end
      end

    end # class EmbeddedValue

  end # class Attribute
end # module Virtus

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
virtus-1.0.0.rc2 lib/virtus/attribute/embedded_value.rb