Sha256: 604fd4aebf46ddb4aaf466aac3452114dce51c9d951cba759646bec3d8e90ec0

Contents?: true

Size: 1.28 KB

Versions: 2

Compression:

Stored size: 1.28 KB

Contents

require_relative "key_value_mapping_rule"

module Lutaml
  module Model
    class KeyValueMapping
      attr_reader :mappings

      def initialize
        @mappings = []
      end

      def map(
        name,
        to: nil,
        render_nil: false,
        with: {},
        delegate: nil,
        child_mappings: nil
      )
        validate!(name, to, with)

        @mappings << KeyValueMappingRule.new(
          name,
          to: to,
          render_nil: render_nil,
          with: with,
          delegate: delegate,
          child_mappings: child_mappings,
        )
      end

      alias map_element map

      def validate!(key, to, with)
        if to.nil? && with.empty?
          msg = ":to or :with argument is required for mapping '#{key}'"
          raise IncorrectMappingArgumentsError.new(msg)
        end

        if !with.empty? && (with[:from].nil? || with[:to].nil?)
          msg = ":with argument for mapping '#{key}' requires :to and :from keys"
          raise IncorrectMappingArgumentsError.new(msg)
        end
      end

      def deep_dup
        self.class.new.tap do |new_mapping|
          new_mapping.instance_variable_set(:@mappings, duplicate_mappings)
        end
      end

      def duplicate_mappings
        @mappings.map(&:deep_dup)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lutaml-model-0.3.15 lib/lutaml/model/key_value_mapping.rb
lutaml-model-0.3.14 lib/lutaml/model/key_value_mapping.rb