module NinjaModel::FinderMethods

Public Instance Methods

all(*args) click to toggle source
# File lib/ninja_model/relation/finder_methods.rb, line 12
def all(*args)
  args.any? ? apply_finder_options(args.first).to_a : to_a
end
exists?(id) click to toggle source
# File lib/ninja_model/relation/finder_methods.rb, line 31
def exists?(id)
  where(primary_key.to_sym => id).limit(1)
  relation.first ? true : false
end
find(*args) click to toggle source
# File lib/ninja_model/relation/finder_methods.rb, line 16
def find(*args)
  options = args.extract_options!

  if options.present?
    apply_finder_options(options).find(*args)
  else
    case args.first
    when :first, :all
      send(args.first)
    else
      find_with_ids(*args)
    end
  end
end
first(*args) click to toggle source
# File lib/ninja_model/relation/finder_methods.rb, line 4
def first(*args)
  if args.any?
    apply_finder_options(args.first).limit(1).to_a.first
  else
    find_first
  end
end

Protected Instance Methods

find_first() click to toggle source
# File lib/ninja_model/relation/finder_methods.rb, line 66
def find_first
  if loaded?
    @records.first
  else
    @first ||= limit(1).to_a[0]
  end
end
find_one(id) click to toggle source
# File lib/ninja_model/relation/finder_methods.rb, line 56
def find_one(id)
  id = id.id if NinjaModel::Base === id

  record = where(primary_key.to_sym => id).first
  unless record
    raise RecordNotFound, "Couldn't find #{@klass.name} with #{primary_key}=#{id}"
  end
  record
end
find_with_ids(*ids) click to toggle source
# File lib/ninja_model/relation/finder_methods.rb, line 38
def find_with_ids(*ids)
  expects_array = ids.first.kind_of?(Array)

  return ids.first if expects_array && ids.first.empty?

  ids = ids.flatten.compact.uniq

  case ids.size
  when 0
    raise RecordNotFound, "Couldn't find #{@klass.name} without an ID"
  when 1
    result = find_one(ids.first)
    expects_array ? [result] : result
  else
    raise NotImplementedError, "Finding by multiple id's is not implemented"
  end
end