Sha256: b4e97ef1b110bed578a815a9ff8df34f58a00dfe3e5927514d5a55d59da92f98

Contents?: true

Size: 1.35 KB

Versions: 6

Compression:

Stored size: 1.35 KB

Contents

# encoding: utf-8
module Dynamoid #:nodoc:

  # This module defines the finder methods that hang off the document at the
  # class level.
  module Finders
    extend ActiveSupport::Concern
    
    module ClassMethods
      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
      
      def find_by_id(id)
        if item = Dynamoid::Adapter.get_item(self.table_name, id)
          obj = self.new(Dynamoid::Adapter.get_item(self.table_name, id))
          obj.new_record = false
          return obj
        else
          return nil
        end
      end
      
      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
    end
  end
  
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
dynamoid-0.1.1 lib/dynamoid/finders.rb
dynamoid-0.1.0 lib/dynamoid/finders.rb
dynamoid-0.0.7 lib/dynamoid/finders.rb
dynamoid-0.0.6 lib/dynamoid/finders.rb
dynamoid-0.0.5 lib/dynamoid/finders.rb
dynamoid-0.0.4 lib/dynamoid/finders.rb