module Modis::Finder::ClassMethods

Public Instance Methods

all() click to toggle source
# File lib/modis/finder.rb, line 15
def all
  unless all_index_enabled?
    raise IndexError, "Unable to retrieve all records of #{name}, "\
      "because you disabled all index. See :enable_all_index for more."
  end

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

  records_to_models(records)
end
attributes_for(redis, id) click to toggle source
# File lib/modis/finder.rb, line 31
def attributes_for(redis, id)
  raise RecordNotFound, "Couldn't find #{name} without an ID" if id.nil?

  attributes = deserialize(record_for(redis, id))

  raise RecordNotFound, "Couldn't find #{name} with id=#{id}" unless attributes['id'].present?

  attributes
end
find(*ids) click to toggle source
# File lib/modis/finder.rb, line 10
def find(*ids)
  models = find_all(ids)
  ids.count == 1 ? models.first : models
end
find_all(ids) click to toggle source
# File lib/modis/finder.rb, line 41
def find_all(ids)
  raise RecordNotFound, "Couldn't find #{name} without an ID" if ids.empty?

  records = Modis.with_connection do |redis|
    blk = proc { |id| record_for(redis, id) }
    ids.count == 1 ? ids.map(&blk) : redis.pipelined { ids.map(&blk) }
  end

  models = records_to_models(records)

  if models.count < ids.count
    missing = ids - models.map(&:id)
    raise RecordNotFound, "Couldn't find #{name} with id=#{missing.first}"
  end

  models
end

Private Instance Methods

model_class(record) click to toggle source
# File lib/modis/finder.rb, line 79
def model_class(record)
  return self if record["type"].blank?

  record["type"].constantize
end
model_for(attributes) click to toggle source
# File lib/modis/finder.rb, line 67
def model_for(attributes)
  cls = model_class(attributes)
  return unless cls == self || cls < self

  cls.new(attributes, new_record: false)
end
record_for(redis, id) click to toggle source
# File lib/modis/finder.rb, line 74
def record_for(redis, id)
  key = sti_child? ? sti_base_key_for(id) : key_for(id)
  redis.hgetall(key)
end
records_to_models(records) click to toggle source
# File lib/modis/finder.rb, line 61
def records_to_models(records)
  records.map do |record|
    model_for(deserialize(record)) unless record.blank?
  end.compact
end