Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'mongo'
- # Simple MongoDB wrapper that stores arbitrary objects using its class name as the key.
- class MongoObjects
- # mongo = MongoObjects.new(options)
- #
- # mongo << ['do', 'ray', 'egon']
- # => { "array" : ['do', 'ray', 'egon'] }
- #
- # mongo << 420
- # => { "fixnum" : 420 }
- #
- # mongo << 3.14159
- # => { "float" : 3.14159 }
- #
- # mongo << { :smoke => 'hash' }
- # => { "hash" : { "smoke" : "hash" } }
- #
- # mongo << /[a-zA-Z]/
- # => { "regexp" : /[a-zA-Z]/ }
- #
- # mongo << "string theory"
- # => { "string" : "string theory" }
- def initialize(options = {})
- @options = options
- @host = @options[:host] || 'localhost'
- @port = @options[:port] || '27017'
- @database = @options[:database] || 'mongo_objects'
- @collection = @options[:collection] || 'objects'
- connect!
- end
- def <<(object)
- save(object)
- end
- def save(object)
- key = key_for(object)
- record = { key => object }
- @db[@collection].insert(record)
- end
- def key_for(object)
- object.class.to_s.downcase.to_sym
- end
- private
- def connect!
- @db = ::Mongo::Connection.new(@host, @port).db(@database)
- if @options[:username]
- @username = @options[:username]
- @password = @options[:password]
- @db.authenticate(@username, @password)
- end
- end
- end
Add Comment
Please, Sign In to add comment