Skip to content

Instantly share code, notes, and snippets.

@aj0strow
Created July 21, 2014 19:51
Show Gist options
  • Save aj0strow/dcaf3cb4344f9429fa79 to your computer and use it in GitHub Desktop.
Save aj0strow/dcaf3cb4344f9429fa79 to your computer and use it in GitHub Desktop.
Mongo cmds with Mongoid config
#!/usr/bin/env ruby
# put in scripts folder, and make executable
# $ chmod +x scripts/mongo
require 'yaml'
HELP = '''
USAGE
$ scripts/mongo [ CMD ] [ -e RACK_ENV ] [ ... ]
DESCRIPTION
Runs mongo#{CMD} configured with config/mongoid.yml.
EXAMPLES
$ scripts/mongo
$ scripts/mongo -e production
$ scripts/mongo dump -e production
$ scripts/mongo import -e staging -c users --file users.json
'''
if %w(--help -h).include?(ARGV.first)
$stderr.puts HELP
exit 1
end
cmd = 'mongo'
unless ARGV.none? || ARGV.first.start_with?('-')
cmd += ARGV.shift
end
env = ENV.fetch('RACK_ENV', 'development')
if %w(-e --env).include?(ARGV.first)
env = ARGV.shift(2).last
end
path = File.expand_path('../../config/mongoid.yml', __FILE__)
config = YAML.load_file(path)[env]['sessions']['default']
user = config['username']
pass = config['password']
host, port = config['hosts'][0].split(':')
db = config['database']
if cmd == 'mongo'
cmd += " #{host}:#{port}/#{db}"
else
cmd += " --host #{host} --port #{port} --db #{db}"
end
cmd += " --username #{user}" unless user.nil?
cmd += " --password #{pass}" unless pass.nil?
system(cmd + ' ' + ARGV.join(' '))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment