Sha256: c1427c7bc65abf564596750a25441f5df96f6932aa3e120e16a6805d7688fa64

Contents?: true

Size: 1.98 KB

Versions: 2

Compression:

Stored size: 1.98 KB

Contents

# frozen_string_literal: true

require 'dry-initializer'

module ROM
  # @api private
  module Initializer
    # @api private
    module DefineWithHook
      # @api private
      def param(*)
        super.tap { __define_with__ }
      end
      ruby2_keywords(:param) if respond_to?(:ruby2_keywords, true)

      # @api private
      def option(*)
        super.tap do
          __define_with__ unless method_defined?(:with)
        end
      end
      ruby2_keywords(:option) if respond_to?(:ruby2_keywords, true)

      # @api private
      def __define_with__
        seq_names = dry_initializer
          .definitions
          .reject { |_, d| d.option }
          .keys
          .join(', ')

        seq_names << ', ' unless seq_names.empty?

        undef_method(:with) if method_defined?(:with)

        class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
          def with(**new_options)
            if new_options.empty?
              self
            else
              self.class.new(#{seq_names}**options, **new_options)
            end
          end
        RUBY
      end
    end

    # @api private
    def self.extended(base)
      base.module_eval do
        undef_method(:with) if method_defined?(:with)

        extend(Dry::Initializer[undefined: false])
        extend(DefineWithHook)
        include(InstanceMethods)
      end
    end

    # @api private
    module InstanceMethods
      # Instance options
      #
      # @return [Hash]
      #
      # @api public
      def options
        @__options__ ||= self.class.dry_initializer.definitions.values.each_with_object({}) do |item, obj|
          obj[item.target] = instance_variable_get(item.ivar)
        end
      end

      define_method(:class, Kernel.instance_method(:class))
      define_method(:instance_variable_get, Kernel.instance_method(:instance_variable_get))

      # This makes sure we memoize options before an object becomes frozen
      #
      # @api public
      def freeze
        options
        super
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rom-core-5.3.2 lib/rom/initializer.rb
rom-core-5.3.1 lib/rom/initializer.rb