Question

I'm creating my own gem and I want to enable user to save data to multiple NOSQL data stores. How can I make this happen? Where should I place the necessary files?

Was it helpful?

Solution

I've done the same thing in my gem. I think you have created an App folder in your gem/engine. Create another folder called "backend" and create classes for each datastore. For my case I created a seperate for Mongo and Redis

module Memberfier
  class RedisStore
    def initialize(redis)
      @redis = redis
    end

    def keys
      @redis.keys
    end

    def []=(key, value)
      value = nil if value.blank?
      @redis[key] = ActiveSupport::JSON.encode(value)
    end

    def [](key)
      @redis[key]
    end

    def clear_database
      @redis.keys.clone.each {|key| @redis.del key }
    end
  end
end


module Memberfier
  class MongoStore
    def initialize(collection)
      @collection = collection
    end

    def keys
      @collection.distinct :_id
    end

    def []=(key, value)
      value = nil if value.blank?
      collection.update({:_id => key},
                        {'$set' => {:value => ActiveSupport::JSON.encode(value)}},
                        {:upsert => true, :safe => true})
    end

    def [](key)
      if document = collection.find_one(:_id => key)
        document["value"]
      else
        nil
      end
    end

    def destroy_entry(key)
      @collection.remove({:_id => key})
    end

    def searchable?
      true
    end

    def clear_database
      collection.drop
    end

    private

    def collection; @collection; end
  end
end

OTHER TIPS

You may have already seen one of Uncle Bob's presentations on application architecture. If not, it's here. I'd recommend having a single boundary object that select models inherit from. That boundary object could have multiple CRUD methods such as find, create, delete. That boundary object could inherit from whatever NOSQL adapter you configure. Example/source: http://hawkins.io/2014/01/pesistence_with_repository_and_query_patterns/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top