Sha256: ac05c9bc5f884bb9e13bd6b5135c9378384a4238307cef0b5afd49653ebfed59

Contents?: true

Size: 1.12 KB

Versions: 1

Compression:

Stored size: 1.12 KB

Contents

module Modis
  module Finders
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def find(id)
        record = attributes_for(id)
        model_class(record).new(record, new_record: false)
      end

      def all
        records = []

        Modis.with_connection do |redis|
          ids = redis.smembers(key_for(:all))
          records = redis.pipelined do
            ids.map { |id| redis.hgetall(key_for(id)) }
          end
        end

        records.map do |record|
          klass = model_class(record)
          klass.new(record, new_record: false)
        end
      end

      def attributes_for(id)
        if id.nil?
          raise RecordNotFound, "Couldn't find #{name} without an ID"
        end
        values = Modis.with_connection { |redis| redis.hgetall(key_for(id)) }
        unless values['id'].present?
          raise RecordNotFound, "Couldn't find #{name} with id=#{id}"
        end
        values
      end

      private

      def model_class(record)
        return self if record["type"].blank?
        return record["type"].constantize
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
modis-1.1.0 lib/modis/finders.rb