Sha256: 007e559ea9ceb258cfdd6a3b31a4bdafa37506d74ca56d614261606d16b2f2ba

Contents?: true

Size: 1.64 KB

Versions: 1

Compression:

Stored size: 1.64 KB

Contents

module ROM
  class Relation
    # Materializes a relation and exposes interface to access the data
    #
    # @api public
    class Loaded
      include Enumerable

      # Source relation
      #
      # @return [Relation]
      #
      # @api private
      attr_reader :source

      # Materialized relation
      #
      # @return [Object]
      #
      # @api private
      attr_reader :collection

      # @api private
      def initialize(source, collection = source.to_a)
        @source = source
        @collection = collection
      end

      # Yield relation tuples
      #
      # @yield [Hash]
      #
      # @api public
      def each(&block)
        return to_enum unless block
        collection.each { |object| yield(object) }
      end

      # @api public
      def new(collection)
        self.class.new(source, collection)
      end

      # Returns a single tuple from the relation if there is one.
      #
      # @raise [ROM::TupleCountMismatchError] if the relation contains more than
      #   one tuple
      #
      # @api public
      def one
        if collection.count > 1
          raise(
            TupleCountMismatchError,
            'The relation consists of more than one tuple'
          )
        else
          collection.first
        end
      end

      # Like [one], but additionally raises an error if the relation is empty.
      #
      # @raise [ROM::TupleCountMismatchError] if the relation does not contain
      #   exactly one tuple
      #
      # @api public
      def one!
        one || raise(
          TupleCountMismatchError,
          'The relation does not contain any tuples'
        )
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rom-0.6.0.beta1 lib/rom/relation/loaded.rb