Module: Perry::FinderMethods

Defined in:
lib/perry/relation/finder_methods.rb

Instance Method Summary collapse

Instance Method Details

#all(options = {}) ⇒ Object



22
23
24
# File 'lib/perry/relation/finder_methods.rb', line 22

def all(options={})
  self.apply_finder_options(options).to_a
end

#apply_finder_options(options) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/perry/relation/finder_methods.rb', line 38

def apply_finder_options(options)
  relation = clone
  return relation unless options

  Perry::Relation::QUERY_METHODS.each do |finder|
    relation = relation.send(finder, options[finder]) if options[finder]
  end

  relation = relation.where(options[:conditions]) if options.has_key?(:conditions)
  relation = relation.where(options[:where]) if options.has_key?(:where)

  relation = relation.includes(options[:include]) if options.has_key?(:include)

  relation = relation.search(options[:search]) if options.has_key?(:search)

  relation = relation.sql(options[:sql]) if options.has_key?(:sql)

  relation = relation.modifiers(options[:modifiers]) if options.has_key?(:modifiers)

  relation
end

#find(ids_or_mode, options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/perry/relation/finder_methods.rb', line 3

def find(ids_or_mode, options={})
  case ids_or_mode
  when Fixnum, String
    self.where(primary_key => ids_or_mode).first(options) || raise(Perry::RecordNotFound, "Could not find #{@klass} with :#{primary_key} = #{ids_or_mode}")
  when Array
    self.where(primary_key => ids_or_mode).all(options).tap do |result|
      unless result.size == ids_or_mode.size
        raise Perry::RecordNotFound, "Couldn't find all #{@klass} with ids (#{ids_or_mode.join(',')}) (expected #{ids_or_mode.size} records but got #{result.size})."
      end
    end
  when :all
    self.all(options)
  when :first
    self.first(options)
  else
    raise ArgumentError, "Unknown arguments for method find"
  end
end

#first(options = {}) ⇒ Object



26
27
28
# File 'lib/perry/relation/finder_methods.rb', line 26

def first(options={})
  self.apply_finder_options(options).limit(1).to_a.first
end

#search(options = {}) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/perry/relation/finder_methods.rb', line 30

def search(options={})
  relation = self
  options.each do |search, *args|
    relation = relation.send(search, *args) if @klass.send(:condition_details, search)
  end
  relation
end