Sha256: 0e88571b34a3d12bf0a2f6c35a30031205796c2f0e985bf0d5107fce7e9d6e4d

Contents?: true

Size: 1.46 KB

Versions: 12

Compression:

Stored size: 1.46 KB

Contents

module NinjaModel
  class RecordNotFound < NinjaModelError; end
  module FinderMethods
    def first(*args)
      if args.any?
        apply_finder_options(args.first).limit(1).to_a.first
      else
        find_first
      end
    end

    def all(*args)
      args.any? ? apply_finder_options(args.first).to_a : to_a
    end

    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

    def exists?(id)
      where(primary_key.to_sym => id).limit(1)
      relation.first ? true : false
    end

    protected

    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

    def find_one(id)
      id = id.id if NinjaModel::Base === id

      where(primary_key.to_sym => id).first
    end

    def find_first
      if loaded?
        @records.first
      else
        @first ||= limit(1).to_a[0]
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
ninja-model-0.7.1 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.7.0 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.6.2 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.6.1 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.6.0 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.5.7 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.5.6 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.5.5 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.5.4 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.5.3 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.5.2 lib/ninja_model/relation/finder_methods.rb
ninja-model-0.5.1 lib/ninja_model/relation/finder_methods.rb