Sha256: af6eca9f43ece4df7a05a49df823935662e9369e42153146f8fef20c233d13b1

Contents?: true

Size: 1.13 KB

Versions: 1

Compression:

Stored size: 1.13 KB

Contents

require 'set'
require 'forwardable'
require 'mongo'

module Flipper
  module Adapters
    class Mongo
      extend Forwardable

      def initialize(collection)
        @collection = collection
        @update_options = {:safe => true, :upsert => true}
      end

      def read(key)
        find_one key
      end

      def write(key, value)
        update key, {'$set' => {'v' => value.to_s}}
      end

      def delete(key)
        remove key
      end

      def set_members(key)
        (find_one(key) || Set.new).to_set
      end

      def set_add(key, value)
        update key, {'$addToSet' => {'v' => value.to_s}}
      end

      def set_delete(key, value)
        update key, {'$pull' => {'v' => value.to_s}}
      end

      private

      def find_one(key)
        doc = @collection.find_one(criteria(key))

        unless doc.nil?
          doc['v']
        end
      end

      def update(key, updates)
        @collection.update criteria(key), updates, @update_options
      end

      def remove(key)
        @collection.remove criteria(key)
      end

      def criteria(key)
        {:_id => key.to_s}
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
flipper-mongo-0.3.0 lib/flipper/adapters/mongo.rb