2011-04-29 21:40:36 +02:00
|
|
|
module CouchRest
|
|
|
|
module Model
|
|
|
|
module Connection
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
def server
|
|
|
|
self.class.server
|
|
|
|
end
|
|
|
|
|
|
|
|
module ClassMethods
|
|
|
|
|
|
|
|
# Overwrite the normal use_database method so that a database
|
|
|
|
# name can be provided instead of a full connection.
|
|
|
|
def use_database(db)
|
2011-04-29 23:06:31 +02:00
|
|
|
@database = prepare_database(db)
|
2011-04-29 21:40:36 +02:00
|
|
|
end
|
|
|
|
|
2011-04-29 23:06:31 +02:00
|
|
|
# Overwrite the default database method so that it always
|
|
|
|
# provides something from the configuration
|
2011-04-29 21:40:36 +02:00
|
|
|
def database
|
2011-04-29 23:06:31 +02:00
|
|
|
super || (@database ||= prepare_database)
|
2011-04-29 21:40:36 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def server
|
|
|
|
@server ||= CouchRest::Server.new(prepare_server_uri)
|
|
|
|
end
|
|
|
|
|
|
|
|
def prepare_database(db = nil)
|
|
|
|
unless db.is_a?(CouchRest::Database)
|
|
|
|
conf = connection_configuration
|
2011-04-29 23:06:31 +02:00
|
|
|
db = [conf[:prefix], db.to_s, conf[:suffix]].reject{|s| s.to_s.empty?}.join(conf[:join])
|
2011-04-29 21:40:36 +02:00
|
|
|
self.server.database!(db)
|
|
|
|
else
|
|
|
|
db
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
|
|
|
def prepare_server_uri
|
|
|
|
conf = connection_configuration
|
|
|
|
userinfo = [conf[:username], conf[:password]].compact.join(':')
|
|
|
|
userinfo += '@' unless userinfo.empty?
|
|
|
|
"#{conf[:protocol]}://#{userinfo}#{conf[:host]}:#{conf[:port]}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def connection_configuration
|
2011-04-29 23:06:31 +02:00
|
|
|
@connection_configuration ||=
|
2011-04-29 21:40:36 +02:00
|
|
|
self.connection.update(
|
2011-04-30 00:34:12 +02:00
|
|
|
(load_connection_config_file[environment.to_sym] || {}).symbolize_keys
|
2011-04-29 21:40:36 +02:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def load_connection_config_file
|
2011-04-30 00:34:12 +02:00
|
|
|
file = connection_config_file
|
|
|
|
connection_config_cache[file] ||=
|
|
|
|
(File.exists?(file) ?
|
|
|
|
YAML::load(ERB.new(IO.read(file)).result) :
|
2011-04-29 23:06:31 +02:00
|
|
|
{ }).symbolize_keys
|
2011-04-29 21:40:36 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def connection_config_cache
|
|
|
|
Thread.current[:connection_config_cache] ||= {}
|
|
|
|
end
|
2011-04-30 00:34:12 +02:00
|
|
|
|
2011-04-29 21:40:36 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|