Sha256: 02b68857081fb2f65d5b6cc0cca04bdc2edfb0df058bb18769b9f8472a2ed7d5

Contents?: true

Size: 1.62 KB

Versions: 7

Compression:

Stored size: 1.62 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
    }
    
    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

7 entries across 7 versions & 1 rubygems

Version Path
mongomodel-0.3.6 lib/mongomodel/support/configuration.rb
mongomodel-0.3.5 lib/mongomodel/support/configuration.rb
mongomodel-0.3.4 lib/mongomodel/support/configuration.rb
mongomodel-0.3.3 lib/mongomodel/support/configuration.rb
mongomodel-0.3.2 lib/mongomodel/support/configuration.rb
mongomodel-0.3.1 lib/mongomodel/support/configuration.rb
mongomodel-0.3.0 lib/mongomodel/support/configuration.rb