Permalink
Browse files

Move query to new document class.

  • Loading branch information...
1 parent 16122a9 commit 64dc4263ee11f69028002d77be1cdfb2ec117e24 @jnunemaker committed Aug 3, 2012
@@ -1,64 +1,24 @@
require 'set'
+require 'forwardable'
require 'mongo'
+require 'flipper/adapters/mongo/document'
module Flipper
module Adapters
class Mongo
- DefaultId = 'flipper'
+ extend Forwardable
def initialize(collection, options = {})
@collection = collection
@options = options
- @mongo_criteria = {:_id => id}
- @mongo_options = {:upsert => true, :safe => true}
end
- def read(key)
- read_key(key)
- end
-
- def write(key, value)
- update '$set' => {key => value}
- end
-
- def delete(key)
- update '$unset' => {key => 1}
- end
-
- def set_add(key, value)
- update '$addToSet' => {key => value}
- end
-
- def set_delete(key, value)
- update '$pull' => {key => value}
- end
-
- def set_members(key)
- read_key(key) { Set.new }.to_set
- end
+ def_delegators :document, :read, :write, :delete, :set_members, :set_add, :set_delete
private
- def id
- @id ||= @options.fetch(:id) { DefaultId }
- end
-
- def update(updates)
- @collection.update(@mongo_criteria, updates, @mongo_options)
- end
-
- def read_key(key, &block)
- load
-
- if block_given?
- @document.fetch(key, &block)
- else
- @document[key]
- end
- end
-
- def load
- @document = @collection.find_one(@mongo_criteria) || {}
+ def document
+ Document.new(@collection, :id => @options[:id])
end
end
end
@@ -0,0 +1,77 @@
+require 'set'
+require 'mongo'
+
+module Flipper
+ module Adapters
+ class Mongo
+ class Document
+ DefaultId = 'flipper'
+
+ def initialize(collection, options = {})
+ @collection = collection
+ @options = options
+ @id = @options.fetch(:id) { DefaultId }
+ @source = @options.fetch(:source) { {} }
+ @criteria = {:_id => @id}
+ @mongo_options = {:safe => true, :upsert => true}
+ end
+
+ def read(key)
+ source[key]
+ end
+
+ def write(key, value)
+ @collection.update @criteria, {'$set' => {key => value}}, @mongo_options
+ @source[key] = value
+ end
+
+ def delete(key)
+ @collection.update @criteria, {'$unset' => {key => 1}}, @mongo_options
+ @source.delete key
+ end
+
+ def set_members(key)
+ members = source.fetch(key) { @source[key] = Set.new }
+
+ if members.is_a?(Array)
+ @source[key] = members.to_set
+ else
+ members
+ end
+ end
+
+ def set_add(key, value)
+ @collection.update @criteria, {'$addToSet' => {key => value}}, @mongo_options
+ set_members(key).add(value)
+ end
+
+ def set_delete(key, value)
+ @collection.update @criteria, {'$pull' => {key => value}}, @mongo_options
+ set_members(key).delete(value)
+ end
+
+ def clear
+ @loaded = nil
+ @source.clear
+ end
+
+ def loaded?
+ @loaded == true
+ end
+
+ private
+
+ def source
+ load unless loaded?
+ @source
+ end
+
+ def load
+ @loaded = true
+ @source.update @collection.find_one(@criteria) || {}
+ end
+
+ end
+ end
+ end
+end
Oops, something went wrong.

0 comments on commit 64dc426

Please sign in to comment.