Sha256: 4e07a0e847524bd84656a25aa41cad9db649b5e8bd43b2399bad9bb663817471

Contents?: true

Size: 1.3 KB

Versions: 2

Compression:

Stored size: 1.3 KB

Contents

module PgObjects
  class Manager
    attr_reader :objects, :config, :log

    def initialize
      raise UnsupportedAdapterError if ActiveRecord::Base.connection.adapter_name != 'PostgreSQL'

      @objects = []
      @config = PgObjects.config
      @log = Logger.new(config.silent)
    end

    def load_files
      config.directories.each do |dir|
        Dir[File.join(dir, '**', "*.{#{config.extensions.join(',')}}")].each do |path|
          @objects << PgObjects::DbObject.new(path)
        end
      end

      self
    end

    def create_objects
      @objects.each { |obj| create_object obj }
    end

    private

    def create_object(obj)
      return if obj.status == :done
      raise CyclicDependencyError if obj.status == :processing

      obj.status = :processing

      create_dependencies(obj.dependencies)

      log.write("creating #{obj.name}")
      ActiveRecord::Base.connection.exec_query obj.sql_query

      obj.status = :done
    end

    def create_dependencies(dependencies)
      dependencies.each { |dep_name| create_object find_object(dep_name) }
    end

    def find_object(dep_name)
      result = @objects.select { |obj| obj.name == dep_name }

      raise AmbiguousDependencyError if result.size > 1
      raise DependencyNotExistError if result.empty?

      result[0]
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pg_objects-0.2.3 lib/pg_objects/manager.rb
pg_objects-0.2.1 lib/pg_objects/manager.rb