Sha256: b3b5227a91daee1485b458157e50d8736d2f60ae55cb7a2c32ec803d8bacfad5

Contents?: true

Size: 1.32 KB

Versions: 4

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

module Vedeu

  module Repositories

    # Some classes expect a certain set of attributes when
    # initialized, this module uses the #defaults method of the class
    # to provide missing attribute keys (and values).
    #
    # @api private
    #
    module Defaults

      include Vedeu::Common

      # Returns a new instance of the class including this module.
      #
      # @note
      #   If a particular key is missing from the attributes
      #   parameter, then it is added with the respective value from
      #   #defaults.
      #
      # @param attributes [Hash]
      # @return [void] A new instance of the class including this
      #   module.
      def initialize(attributes = {})
        defaults.merge!(validate(attributes)).each do |key, value|
          instance_variable_set("@#{key}", value || defaults.fetch(key))
        end
      end

      private

      # @return [Hash<void>]
      def defaults
        {}
      end

      # @param attributes [Hash]
      # @macro raise_invalid_syntax
      # @return [Hash]
      def validate(attributes)
        fail Vedeu::Error::InvalidSyntax,
             'Argument :attributes is not a Hash.' unless hash?(attributes)

        attributes.keep_if { |key, _| defaults.key?(key) }
      end

    end # Defaults

  end # Repositories

end # Vedeu

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
vedeu-0.8.9 lib/vedeu/repositories/defaults.rb
vedeu-0.8.8 lib/vedeu/repositories/defaults.rb
vedeu-0.8.7 lib/vedeu/repositories/defaults.rb
vedeu-0.8.6 lib/vedeu/repositories/defaults.rb