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

- (Dynamoid::Document/Array) method_missing(method, *args)

Find using exciting method_missing finders attributes. Uses criteria chains under the hood to accomplish this neatness.

Examples:

find a user by a first name

User.find_by_first_name('Josh')

find all users by first and last name

User.find_all_by_first_name_and_last_name('Josh', 'Symonds')

Returns:

  • (Dynamoid::Document/Array)

    the found object, or an array of found objects if all was somewhere in the method

Since:

  • 0.2.0



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/dynamoid/finders.rb', line 63

def method_missing(method, *args)
  if method =~ /find/
    finder = method.to_s.split('_by_').first
    attributes = method.to_s.split('_by_').last.split('_and_')

    chain = Dynamoid::Criteria::Chain.new(self)
    chain.query = Hash.new.tap {|h| attributes.each_with_index {|attr, index| h[attr.to_sym] = args[index]}}
    
    if finder =~ /all/
      return chain.all
    else
      return chain.first
    end
  else
    super
  end
end

Instance Method Details

- (Dynamoid::Document) find(*ids)

Find one or many objects, specified by one id or an array of ids.

Parameters:

  • *id (Array/String)

    an array of ids or one single id

Returns:

  • (Dynamoid::Document)

    one object or an array of objects, depending on whether the input was an array or not

Since:

  • 0.2.0



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/dynamoid/finders.rb', line 18

def find(*ids)

  options = if ids.last.is_a? Hash
              ids.slice!(-1)
            else
              {}
            end

  ids = Array(ids.flatten.uniq)
  if ids.count == 1
    self.find_by_id(ids.first, options)
  else
    items = Dynamoid::Adapter.read(self.table_name, ids, options)
    items[self.table_name].collect{|i| self.build(i).tap { |o| o.new_record = false } }
  end
end

- (Dynamoid::Document) find_by_id(id, options = {})

Find one object directly by id.

Parameters:

  • id (String)

    the id of the object to find

Returns:

Since:

  • 0.2.0



42
43
44
45
46
47
48
49
50
# File 'lib/dynamoid/finders.rb', line 42

def find_by_id(id, options = {})
  if item = Dynamoid::Adapter.read(self.table_name, id, options)
    obj = self.new(item)
    obj.new_record = false
    return obj
  else
    return nil
  end
end