Sha256: d4a9f8f3b0d5a91b63ef9776a6942a032bdd3c6fa8a1bc4e76c6b2713dfe21e7

Contents?: true

Size: 1.21 KB

Versions: 3

Compression:

Stored size: 1.21 KB

Contents

require 'spyke/exceptions'

module Spyke
  class Relation
    include Enumerable

    attr_reader :klass, :params
    attr_writer :params
    delegate :to_ary, :[], :empty?, :last, :size, :metadata, to: :find_some

    def initialize(klass, options = {})
      @klass, @options, @params = klass, options, {}
    end

    def where(conditions = {})
      relation = clone
      relation.params = params.merge(conditions)
      relation
    end

    # Overrides Enumerable find
    def find(id)
      scoping { klass.find(id) }
    end

    def find_one
      @find_one ||= klass.new_from_result(fetch)
    end

    def find_some
      @find_some ||= klass.new_collection_from_result(fetch)
    end

    def each
      find_some.each { |record| yield record }
    end

    def uri
      @options[:uri]
    end

    private

      def method_missing(name, *args, &block)
        if klass.respond_to?(name)
          scoping { klass.send(name, *args) }
        else
          super
        end
      end

      # Keep hold of current scope while running a method on the class
      def scoping
        previous, klass.current_scope = klass.current_scope, self
        yield
      ensure
        klass.current_scope = previous
      end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
spyke-1.7.1 lib/spyke/relation.rb
spyke-1.7.0 lib/spyke/relation.rb
spyke-1.6.0 lib/spyke/relation.rb