MongoSync Ruby Gem

In my previous post, I had written about my mongo-sync shell script that allows you to sync Local and Remote Mongo Databases. I spent the last day converting it into a Ruby Gem so that you can perform actions using nice Rake Tasks and invoke the commands from Rails Console or irb.

MongoSync Ruby Gem Demo GIF

If the gif above wasn’t explanatory enough, start by adding it to your Gemfile:

1
gem 'mongo_sync',   group: :development

Bundle and run the generator to create configuration template:

1
2
$ bundle
$ rails g mongo_sync:config

Edit the newly created config/mongo_sync.yml, putting in details of your remote and local DBs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
local:
  db: 'local_db_name'

remote:
  db: 'remote_db_name'
  host:
    url: 'some.remoteurl.com'
    port: 27017
  access:
    username: 'remote_mongo_user'
    password: 'remote_mongo_pass'

# For Heroku MongoDB URLs, here's the legend:
# mongodb://username:[email protected]:port/db_name

# All fields are required

To Sync, use these rake tasks:

1
2
rake mongo_sync:push       # Push DB to Remote
rake mongo_sync:pull       # Pull DB to Local

You can use it in rails console as well:

1
2
3
4
5
6
7
require 'mongo_sync'

MongoSync.pull
MongoSync.push

# You can also pass path to a custom config file
MongoSync.push "path/to/custom/mongo_sync.yml"

A few important things to note are:

  • mongodb needs to be installed on your system (obviously)
  • Pushing/Pulling overwrites the Target DB
  • It’s a good idea to keep your mongo_sync.yml in .gitignore or load the values from the ENV

There’s still much to do but for now it should work perfectly with your Rails Projects. Find me on twitter if you have something to add.