Sha256: 731cc48a766c7761005e549474f4c571b3f17b2e0215c0a1c1ebfcf765d12471

Contents?: true

Size: 1.66 KB

Versions: 15

Compression:

Stored size: 1.66 KB

Contents

require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/except'

module MongoModel
  class Configuration
    def initialize(options)
      set_options!(options)
    end
    
    def host
      @options['host']
    end
    
    def port
      @options['port']
    end
    
    def database
      @options['database']
    end
    
    def username
      @options['username']
    end
    
    def password
      @options['password']
    end
    
    def establish_connection
      @connection ||= Mongo::Connection.new(host, port, connection_options)
      @database = @connection.db(database)
      @database.authenticate(username, password) if username.present?
      @database
    end
    
    def use_database(database)
      @options['database'] = database
      establish_connection
    end
    
    def connection_options
      @options.except('host', 'port', 'database', 'username', 'password').symbolize_keys
    end
    
    def set_options!(options)
      case options
      when Hash
        @options = DEFAULTS.merge(options).stringify_keys
      when String
        set_options!(parse(options))
      end
    end
    
    DEFAULTS = {
      'host'      => 'localhost',
      'port'      => 27017,
      'database'  => 'mongomodel-default',
      'pool_size' => 5,
      'timeout'   => 5,
      'logger'    => MongoModel.logger
    }
    
    def self.defaults
      new({})
    end
  
  private
    def parse(str)
      uri = URI.parse(str)
      
      {
        'host'     => uri.host,
        'port'     => uri.port,
        'database' => uri.path.gsub(/^\//, ''),
        'username' => uri.user,
        'password' => uri.password
      }
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
mongomodel-0.2.20 lib/mongomodel/support/configuration.rb
mongomodel-0.2.19 lib/mongomodel/support/configuration.rb
mongomodel-0.2.18 lib/mongomodel/support/configuration.rb
mongomodel-0.2.17 lib/mongomodel/support/configuration.rb
mongomodel-0.2.16 lib/mongomodel/support/configuration.rb
mongomodel-0.2.15 lib/mongomodel/support/configuration.rb
mongomodel-0.2.14 lib/mongomodel/support/configuration.rb
mongomodel-0.2.13 lib/mongomodel/support/configuration.rb
mongomodel-0.2.12 lib/mongomodel/support/configuration.rb
mongomodel-0.2.11 lib/mongomodel/support/configuration.rb
mongomodel-0.2.10 lib/mongomodel/support/configuration.rb
mongomodel-0.2.9 lib/mongomodel/support/configuration.rb
mongomodel-0.2.8 lib/mongomodel/support/configuration.rb
mongomodel-0.2.7 lib/mongomodel/support/configuration.rb
mongomodel-0.2.6 lib/mongomodel/support/configuration.rb