Sha256: 490f13195b83dd53ae44a7e2c5b69ff80db6d18624c87fbab3bbf4fc1b4d3c2a

Contents?: true

Size: 985 Bytes

Versions: 3

Compression:

Stored size: 985 Bytes

Contents

module Fortnox
  module API
    module Types
      class Model < Dry::Struct
        constructor_type(:schema)

        def initialize( input_attributes )
          if (missing_key = first_missing_required_key( input_attributes ))
            raise Fortnox::API::MissingAttributeError.new( "Missing attribute #{ missing_key.inspect } in attributes: #{ input_attributes }" )
          end

          super
        end

      private

        def missing_keys( attributes )
          non_nil_attributes = attributes.select{ |_,value| !value.nil? }

          attribute_keys = non_nil_attributes.keys
          schema_keys =  self.class.schema.keys

          schema_keys - attribute_keys
        end

        def first_missing_required_key( attributes )
          missing_keys( attributes ).find do |name|
            attribute = self.class.schema[ name ]
            attribute.respond_to?(:options) && attribute.options[:required]
          end
        end
      end

    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
fortnox-api-0.5.2 lib/fortnox/api/types/model.rb
fortnox-api-0.5.1 lib/fortnox/api/types/model.rb
fortnox-api-0.5.0 lib/fortnox/api/types/model.rb