Sha256: 034c2a2397f4b96faf76b5cb6d65a062f444d0b2e97a57be1cc38a6a490a385e

Contents?: true

Size: 1.85 KB

Versions: 8

Compression:

Stored size: 1.85 KB

Contents

require 'pathname'

require 'dry/core/inflector'

require 'rom/types'
require 'rom/initializer'
require 'rom/setup/auto_registration_strategies/no_namespace'
require 'rom/setup/auto_registration_strategies/with_namespace'
require 'rom/setup/auto_registration_strategies/custom_namespace'

module ROM
  class AutoRegistration
    extend Initializer

    NamespaceType = Types::Strict::Bool | Types::Strict::String
    PathnameType = Types.Constructor(Pathname, &Kernel.method(:Pathname))
    DEFAULT_MAPPING = {
      relations: :relations,
      mappers: :mappers,
      commands: :commands
    }.freeze

    param :directory, type: PathnameType

    option :namespace, type: NamespaceType, default: -> { true }

    option :component_dirs, type: Types::Strict::Hash, default: -> { DEFAULT_MAPPING }

    option :globs, default: -> {
      Hash[
        component_dirs.map { |component, path|
          [component, directory.join("#{path}/**/*.rb")]
        }
      ]
    }

    def relations
      load_entities(:relations)
    end

    def commands
      load_entities(:commands)
    end

    def mappers
      load_entities(:mappers)
    end

    private

    def load_entities(entity)
      Dir[globs[entity]].map do |file|
        require file
        klass_name =
          case namespace
          when String
            AutoRegistrationStrategies::CustomNamespace.new(
              namespace: namespace, file: file, directory: directory
            ).call
          when TrueClass
            AutoRegistrationStrategies::WithNamespace.new(
              file: file, directory: directory
            ).call
          when FalseClass
            AutoRegistrationStrategies::NoNamespace.new(
              file: file, directory: directory, entity: component_dirs.fetch(entity)
            ).call
          end

        Dry::Core::Inflector.constantize(klass_name)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 2 rubygems

Version Path
rom-3.3.3 lib/rom/setup/auto_registration.rb
rom-3.3.2 lib/rom/setup/auto_registration.rb
rom-core-4.0.0.beta3 lib/rom/setup/auto_registration.rb
rom-3.3.1 lib/rom/setup/auto_registration.rb
rom-core-4.0.0.beta2 lib/rom/setup/auto_registration.rb
rom-3.3.0 lib/rom/setup/auto_registration.rb
rom-core-4.0.0.beta1 lib/rom/setup/auto_registration.rb
rom-3.2.3 lib/rom/setup/auto_registration.rb