Created
February 27, 2015 12:30
-
-
Save mudge/7a84d93e060f7c11963f to your computer and use it in GitHub Desktop.
A helper class to parse MongoDB connection strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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