lib/mongodoc/connection.rb in mongodoc-0.2.1 vs lib/mongodoc/connection.rb in mongodoc-0.2.2

- old
+ new

@@ -1,25 +1,88 @@ module MongoDoc - mattr_accessor :config, :config_path, :connection, :database - self.config_path = './mongodb.yml' + class NoConnectionError < RuntimeError; end + class UnsupportedServerVersionError < RuntimeError; end - def self.connect_to_database(name = nil, host = nil, port = nil, options = nil, force_connect = false) - name ||= configuration['name'] - self.database = ((!force_connect && connection)|| connect(host, port, options)).db(name) - raise NoDatabaseError unless database - database - end + module Connection - def self.connect(*args) - opts = args.extract_options! - host = args[0] || configuration['host'] || configuration['host_pairs'] - port = args[1] || configuration['port'] - options = opts.empty? ? configuration['options'] || {} : opts - self.connection = Mongo::Connection.new(host, port, options) - raise NoConnectionError unless connection - connection - end + extend self - def self.configuration - self.config ||= File.exists?(config_path || '') ? YAML.load_file(config_path) : {} + attr_writer :config_path, :env, :host, :name, :options, :port, :strict + + def config_path + @config_path || default_path + end + + def configuration + @configuration ||= File.exists?(config_path) ? YAML.load_file(config_path)[env] : {} + end + + def connection + @connection ||= connect + end + + def database + @database ||= connection.db(name, :strict => strict) + end + + def env + if rails? + Rails.env + else + @env ||= 'development' + end + end + + def host + @host ||= configuration['host'] + end + + def name + @name ||= configuration['name'] || default_name + end + + def options + @options ||= configuration['options'] || {} + end + + def port + @port ||= configuration['port'] + end + + def strict + @strict ||= configuration['strict'] || false + end + + private + + def connect + connection = Mongo::Connection.new(host, port, options) + raise NoConnectionError unless connection + verify_server_version(connection) + connection + end + + def default_name + if rails? + "#{Rails.root.basename}_#{Rails.env}" + else + "mongodoc" + end + end + + def default_path + if rails? + Rails.root + 'config/mongodb.yml' + else + './mongodb.yml' + end + end + + def rails? + Object.const_defined?("Rails") + end + + def verify_server_version(connection) + raise UnsupportedServerVersionError.new('MongoDoc requires at least mongoDB version 1.3.2') unless connection.server_version >= "1.3.2" + end end end