Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Created October 5, 2011 17:13
Show Gist options
  • Save earlonrails/1265046 to your computer and use it in GitHub Desktop.
Save earlonrails/1265046 to your computer and use it in GitHub Desktop.
Use a replicaSet with Ruby Ree, Rails 2.3.4, Mongoid 1.9.2 and Mongo 1.0.9. Mongoid.database= Errors needs admin, so connect to admin then swap db after 2 seconds.
require 'mongoid'
# MongoDB ENV vars
File.open(File.join(RAILS_ROOT, 'config/mongodb.yml'), 'r') do |f|
@settings = YAML.load(f)[RAILS_ENV]
end
port = @settings["port"].nil? ? Mongo::Connection::DEFAULT_PORT : @settings["port"]
host_arr = @settings["host"]
connect = Mongo::Connection.multi([[host_arr[0], 27017], [host_arr[1], 27017], [host_arr[2], 27017]], :read_secondary => true)
db = connect.db(@settings["database"])
admin_db = connect.db("admin")
admin_db.authenticate(@settings["username"], @settings["password"])
db.authenticate(@settings["username"], @settings["password"])
Mongoid.database = admin_db
puts "Authenticating mongo..."
sleep 2
Mongoid.database = db
Mongoid.configure do |config|
config.allow_dynamic_fields = true
end
defaults: &defaults
host: ["A", "B", "C"]
username: 'user'
password: 'iRuser'
allow_dynamic_fields: true
parameterize_keys: true
persist_in_safe_mode: true
raise_not_found_error: true
reconnect_time: 3
use_object_ids: false
development:
<<: *defaults
database: 'my_database'
test:
<<: *defaults
database: 'my_test_database'
production:
host: ["A", "B", "C"]
username: 'user'
password: 'iRuser'
port: 27017
database: my_database
allow_dynamic_fields: true
parameterize_keys: true
persist_in_safe_mode: true
raise_not_found_error: true
reconnect_time: 3
use_object_ids: false
class FakeActiverecord
include Mongoid::Document
field :fake_mongoid_id, :tyge => Integer, :default => 0
# This is to fake activerecord association
def fake_mongoid
FakeMongoid.find(self.fake_mongoid_id)
end
end
class FakeMongoid < ActiveRecord::Base
# This is to fake Mongoid association
def fake_activerecords
FakeActiverecord.where(:fake_mongoid_id => self.id.to_s)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment