Guest User

Untitled

a guest
Apr 8th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. require 'mongo'
  2.  
  3. # Simple MongoDB wrapper that stores arbitrary objects using its class name as the key.
  4. class MongoObjects
  5.  
  6. # mongo = MongoObjects.new(options)
  7. #
  8. # mongo << ['do', 'ray', 'egon']
  9. # => { "array" : ['do', 'ray', 'egon'] }
  10. #
  11. # mongo << 420
  12. # => { "fixnum" : 420 }
  13. #
  14. # mongo << 3.14159
  15. # => { "float" : 3.14159 }
  16. #
  17. # mongo << { :smoke => 'hash' }
  18. # => { "hash" : { "smoke" : "hash" } }
  19. #
  20. # mongo << /[a-zA-Z]/
  21. # => { "regexp" : /[a-zA-Z]/ }
  22. #
  23. # mongo << "string theory"
  24. # => { "string" : "string theory" }
  25. def initialize(options = {})
  26. @options = options
  27. @host = @options[:host] || 'localhost'
  28. @port = @options[:port] || '27017'
  29. @database = @options[:database] || 'mongo_objects'
  30. @collection = @options[:collection] || 'objects'
  31. connect!
  32. end
  33.  
  34. def <<(object)
  35. save(object)
  36. end
  37.  
  38. def save(object)
  39. key = key_for(object)
  40. record = { key => object }
  41. @db[@collection].insert(record)
  42. end
  43.  
  44. def key_for(object)
  45. object.class.to_s.downcase.to_sym
  46. end
  47.  
  48. private
  49.  
  50. def connect!
  51. @db = ::Mongo::Connection.new(@host, @port).db(@database)
  52. if @options[:username]
  53. @username = @options[:username]
  54. @password = @options[:password]
  55. @db.authenticate(@username, @password)
  56. end
  57. end
  58.  
  59. end
Add Comment
Please, Sign In to add comment