Module: Modis::Finder::ClassMethods

Defined in:
lib/modis/finder.rb

Instance Method Summary collapse

Instance Method Details

#allObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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 |pipeline|
      ids.map { |id| record_for(pipeline, id) }
    end
  end

  records_to_models(records)
end

#attributes_for(redis, id) ⇒ Object

Raises:



31
32
33
34
35
36
37
38
39
# 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) ⇒ Object



10
11
12
13
# File 'lib/modis/finder.rb', line 10

def find(*ids)
  models = find_all(ids)
  ids.count == 1 ? models.first : models
end

#find_all(ids) ⇒ Object

Raises:



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# 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|
    if ids.count == 1
      ids.map { |id| record_for(redis, id) }
    else
      redis.pipelined do |pipeline|
        ids.map { |id| record_for(pipeline, id) }
      end
    end
  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