Module: Dynamoid::Finders::ClassMethods

Defined in:
lib/dynamoid/finders.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/dynamoid/finders.rb', line 26

def method_missing(method, *args)
  if method =~ /find/
    finder = method.to_s.split('_by_').first
    attributes = method.to_s.split('_by_').last.split('_and_')
    
    results = if index = self.indexes.find {|i| i == attributes.sort.collect(&:to_sym)}
      ids = Dynamoid::Adapter.get_item(self.index_table_name(index), self.key_for_index(index, args))
      if ids.nil? || ids.empty?
        []
      else
        self.find(ids[:ids].to_a)
      end
    else
      if Dynamoid::Config.warn_on_scan
        puts 'Queries without an index are forced to use scan and are generally much slower than indexed queries!'
        puts "You can index this query by adding this to #{self.to_s.downcase}.rb: index [#{attributes.sort.collect{|attr| ":#{attr}"}.join(', ')}]"
      end
      scan_hash = {}
      attributes.each_with_index {|attr, index| scan_hash[attr.to_sym] = args[index]}
      Dynamoid::Adapter.scan(self.table_name, scan_hash).collect {|hash| self.new(hash)}
    end
    
    if finder =~ /all/
      return Array(results)
    else
      return results.first
    end
  end
end

Instance Method Details

#find(*id) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/dynamoid/finders.rb', line 10

def find(*id)
  id = Array(id.flatten.uniq)
  if id.count == 1
    self.find_by_id(id.first)
  else
    items = Dynamoid::Adapter.batch_get_item(self.table_name => id)
    items[self.table_name].collect{|i| o = self.build(i); o.new_record = false; o}
  end
end

#find_by_id(id) ⇒ Object



20
21
22
23
24
# File 'lib/dynamoid/finders.rb', line 20

def find_by_id(id)
  obj = self.new(Dynamoid::Adapter.get_item(self.table_name, id))
  obj.new_record = false
  obj    
end