Skip to content

Instantly share code, notes, and snippets.

@mudge
Created February 27, 2015 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mudge/7a84d93e060f7c11963f to your computer and use it in GitHub Desktop.
Save mudge/7a84d93e060f7c11963f to your computer and use it in GitHub Desktop.
A helper class to parse MongoDB connection strings
module MongoDB
class URI
attr_reader :uri
def initialize(uri)
@uri = uri
end
def username
matches[:username]
end
def password
matches[:password]
end
def hosts
matches[:hosts].split(',')
end
def database
matches[:database]
end
def options
matches[:options]
end
private
def matches
@matches ||= uri.match(
%r{
mongodb://
(?:
(?<username> [^:]+) : (?<password> [^@]+) @
)?
(?<hosts>
(?:
(?: [^:/]+? ) # host name
(?: : \d+ )? # port
,?
)+
)
(?:
/(?<database> [^?]+)
)?
(?:
\?(?<options> .+)
)?
}x
)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment