Sha256: 7957b98970edefab32b585a7f0922f459307b9257765a82fdd5ef0368981e7bd

Contents?: true

Size: 1.71 KB

Versions: 4

Compression:

Stored size: 1.71 KB

Contents

require 'erb'
require 'yaml'

module Kuby
  module Plugins
    module RailsApp
      class UnsupportedDatabaseError < StandardError; end

      class Database
        ADAPTER_MAP = {
          sqlite3: Sqlite,
          mysql2: MySQL,
          postgresql: Postgres
        }.freeze

        def self.get(rails_app)
          if rails_app.manage_database?
            new(rails_app)
          end
        end

        def self.get_adapter(adapter_name)
          ADAPTER_MAP.fetch(adapter_name) do
            raise UnsupportedDatabaseError, "Kuby does not support the '#{adapter}' "\
              'database adapter'
          end
        end

        attr_reader :rails_app

        def initialize(rails_app)
          @rails_app = rails_app
        end

        def plugin
          @plugin ||= self.class
            .get_adapter(adapter_name)
            .new(rails_app.environment, db_configs)
        end

        def adapter_name
          @adapter_name ||= db_config['adapter'].to_sym
        end

        alias_method :plugin_name, :adapter_name

        private

        def db_config
          @db_config ||= db_configs[rails_app.environment.name]
        end

        def db_configs
          @db_configs ||= YAML.load(ERB.new(File.read(db_config_path)).result)
        end

        def db_config_path
          @db_config_path ||= begin
            db_config_paths.first or
              raise "Couldn't find database config at #{rails_app.root}"
          end
        end

        def db_config_paths
          @db_config_paths ||=
            Dir.glob(
              File.join(
                rails_app.root, 'config', 'database.{yml,erb,yml.erb,yaml,yaml.erb}'
              )
            )
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
kuby-core-0.9.1 lib/kuby/plugins/rails_app/database.rb
kuby-core-0.9.0 lib/kuby/plugins/rails_app/database.rb
kuby-core-0.8.1 lib/kuby/plugins/rails_app/database.rb
kuby-core-0.8.0 lib/kuby/plugins/rails_app/database.rb