Created
September 13, 2011 18:03
-
-
Save mediocretes/1214530 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Cie | |
class Data | |
@logger = defined?(RAILS_DEFAULT_LOGGER) ? RAILS_DEFAULT_LOGGER : SimpleLogger.instance | |
@wrappers = Hash.new | |
def self.connect(slave_ok) | |
puts "Cie::Data.connect!" | |
@logger.debug "Regenerating #{slave_ok ? '' : 'Writable '}Writable Mongo Connection #{CIE_CONNECTION.inspect}" | |
options = CIE_CONNECTION.merge(:slave_ok => slave_ok) | |
options[:logger] = @logger if options[:debug] | |
Mongo::Connection.new(options[:server], options[:port], options).db(CIE_CONNECTION[:db_name]) | |
end | |
def self.reconnect | |
@readable_db.connection.connect_to_master unless @readable_db.nil? | |
@writeable_db.connection.connect_to_master unless @writeable_db.nil? | |
end | |
def self.wrap(collection_name) | |
@wrappers[collection_name] ||= CollectionWrapper.new(collection_name, @writable_db ||= connect(false), @readable_db ||= connect(true)) | |
end | |
def self.ping | |
wrap('Test') | |
end | |
def self.tags | |
wrap 'TagList' | |
end | |
def self.events | |
wrap('Events') | |
end | |
#... many more like this | |
end | |
class CollectionWrapper | |
READABLE_OK = [:find, :find_one, :group, :count, :distinct] | |
def initialize(collection, readable, writable) | |
@readable = readable[collection] | |
@writable = writable[collection] | |
end | |
def find(*args) | |
@readable.find(*args) | |
end | |
def find_one(*args) | |
@readable.find_one(*args) | |
end | |
def insert(*args) | |
@writable.insert(*args) | |
end | |
def update(*args) | |
@writable.update(*args) | |
end | |
def method_missing(method, *args, &block) | |
RAILS_DEFAULT_LOGGER.debug "Call to data/method_missing - consider defining your query (#{method})" if defined? RAILS_DEFAULT_LOGGER | |
if READABLE_OK.include? method | |
@readable.send(method, *args, &block) | |
else | |
@writable.send(method, *args, &block) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment