Skip to content

Instantly share code, notes, and snippets.

@picatz
Created January 4, 2017 01:49
Show Gist options
  • Save picatz/56a30b0ebb228ef38daa76e58f822df0 to your computer and use it in GitHub Desktop.
Save picatz/56a30b0ebb228ef38daa76e58f822df0 to your computer and use it in GitHub Desktop.
require 'mongo' # must have this to work
def connect_to_db(args={})
ip = args[:ip] || '127.0.0.1'
port = args[:port].to_s || '27017'
begin
client = Mongo::Client.new(["#{ip}:#{port}"])
rescue Mongo::Auth::Unauthorized, Mongo::Error => e
puts "Error #{e.class}: #{e.message}"
end
end
# Example usage:
# Connect to local db with all defaults
connect_to_db
# Connect to db with an IP address
connect_to_db(ip: '127.0.0.1')
# Connect to a db wth an IP address and port
connect_to_db(ip: '127.0.0.1', port: '27107')
# and port can be passed in as an integer
connect_to_db(ip: '127.0.0.1', port: 27107)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment