Sha256: a357cd5fe735966aa0524ed69869508242fa9f70a20b2e9067715072e96b732d

Contents?: true

Size: 1.59 KB

Versions: 12

Compression:

Stored size: 1.59 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    # A mixin to extend cops in order to determine the database type.
    #
    # This module automatically detect an adapter from `development` environment
    # in `config/database.yml` or the environment variable `DATABASE_URL`
    # when the `Database` option is not set.
    module DatabaseTypeResolvable
      MYSQL = 'mysql'
      POSTGRESQL = 'postgresql'

      def database
        cop_config['Database'] || database_from_yaml || database_from_env
      end

      private

      def database_from_yaml
        return unless database_yaml

        case database_adapter
        when 'mysql2', 'trilogy'
          MYSQL
        when 'postgresql', 'postgis'
          POSTGRESQL
        end
      end

      def database_from_env
        url = ENV['DATABASE_URL'].presence
        return unless url

        case url
        when %r{\A(mysql2|trilogy)://}
          MYSQL
        when %r{\Apostgres(ql)?://}
          POSTGRESQL
        end
      end

      def database_yaml
        return unless File.exist?('config/database.yml')

        yaml = if YAML.respond_to?(:unsafe_load_file)
                 YAML.unsafe_load_file('config/database.yml')
               else
                 YAML.load_file('config/database.yml')
               end
        return unless yaml.is_a? Hash

        config = yaml['development']
        return unless config.is_a?(Hash)

        config
      rescue Psych::SyntaxError
        # noop
      end

      def database_adapter
        database_yaml['adapter'] || database_yaml.first.last['adapter']
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 4 rubygems

Version Path
rubocop-rails-2.27.0 lib/rubocop/cop/mixin/database_type_resolvable.rb
rubocop-rails-2.26.2 lib/rubocop/cop/mixin/database_type_resolvable.rb
rubocop-rails-2.26.1 lib/rubocop/cop/mixin/database_type_resolvable.rb
rubocop-rails-2.26.0 lib/rubocop/cop/mixin/database_type_resolvable.rb
blacklight-spotlight-3.6.0.beta8 vendor/bundle/ruby/3.2.0/gems/rubocop-rails-2.25.1/lib/rubocop/cop/mixin/database_type_resolvable.rb
rubocop-rails-2.25.1 lib/rubocop/cop/mixin/database_type_resolvable.rb
katalyst-govuk-formbuilder-1.9.2 vendor/bundle/ruby/3.3.0/gems/rubocop-rails-2.25.0/lib/rubocop/cop/mixin/database_type_resolvable.rb
rubocop-rails-2.24.1 lib/rubocop/cop/mixin/database_type_resolvable.rb
rubocop-rails-2.24.0 lib/rubocop/cop/mixin/database_type_resolvable.rb
mlh-rubocop-config-1.0.3 vendor/bundle/ruby/3.2.0/gems/rubocop-rails-2.23.1/lib/rubocop/cop/mixin/database_type_resolvable.rb
rubocop-rails-2.23.1 lib/rubocop/cop/mixin/database_type_resolvable.rb
rubocop-rails-2.23.0 lib/rubocop/cop/mixin/database_type_resolvable.rb