Sha256: 7679b46e3115a9afdbd1deeb95574fb3f21d06468c0de7d0a1c2d9213c3d0871

Contents?: true

Size: 1.11 KB

Versions: 4

Compression:

Stored size: 1.11 KB

Contents

require 'pathname'

require 'rom/support/constants'
require 'rom/support/inflector'
require 'rom/support/options'

module ROM
  class AutoRegistration
    include Options

    option :namespace, reader: true, type: [TrueClass, FalseClass], default: true

    attr_reader :globs, :directory

    def initialize(directory, options = EMPTY_HASH)
      super
      @directory = directory
      @globs = Hash[[:relations, :commands, :mappers].map { |name|
        [name, Pathname(directory).join("#{name}/**/*.rb")]
      }]
    end

    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
        Inflector.constantize(const_name(entity, file))
      end
    end

    def const_name(entity, file)
      name =
        if namespace
          file.gsub("#{directory.dirname}/", '')
        else
          file.gsub("#{directory}/#{entity}/", '')
        end.gsub('.rb', '')

      Inflector.camelize(name)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rom-1.0.0 lib/rom/setup/auto_registration.rb
rom-1.0.0.rc1 lib/rom/setup/auto_registration.rb
rom-1.0.0.beta2 lib/rom/setup/auto_registration.rb
rom-1.0.0.beta1 lib/rom/setup/auto_registration.rb