lib/axiom/algebra/rename.rb

Summary

Maintainability
A
0 mins
Test Coverage
# encoding: utf-8

module Axiom
  module Algebra

    # Rename attributes in the header
    class Rename < Relation
      include Relation::Operation::Unary
      include Equalizer.new(:operand, :aliases)

      # The aliases for the relation
      #
      # @return [Aliases]
      #
      # @api private
      attr_reader :aliases

      # The relation sort order
      #
      # @return [Operation::Sorted::DirectionSet]
      #
      # @api private
      attr_reader :directions

      # Initialize a Rename
      #
      # @param [Relation] operand
      #   the relation to rename
      # @param [Hash, Aliases] aliases
      #   the old and new attribute names
      #
      # @return [undefined]
      #
      # @api private
      def initialize(operand, aliases)
        super(operand)
        @aliases    = Aliases.coerce(@header, aliases)
        @header     = @header.rename(@aliases)
        @directions = operand.directions.rename(@aliases)
      end

      # Iterate over each tuple in the set
      #
      # @example
      #   rename = Rename.new(operand, aliases)
      #   rename.each { |tuple| ... }
      #
      # @yield [tuple]
      #
      # @yieldparam [Tuple] tuple
      #   each tuple in the set
      #
      # @return [self]
      #
      # @api public
      def each
        return to_enum unless block_given?
        operand.each { |tuple| yield tuple.rename(header) }
        self
      end

      # Insert a relation into the Rename
      #
      # @example
      #   new_relation = rename.insert(other)
      #
      # @param [Relation] other
      #
      # @return [Rename]
      #
      # @api public
      def insert(other)
        other = coerce(other)
        operand.insert(other.rename(aliases.inverse)).rename(aliases)
      end

      # Delete a relation from the Rename
      #
      # @example
      #   new_relation = rename.delete(other)
      #
      # @param [Relation] other
      #
      # @return [Rename]
      #
      # @api public
      def delete(other)
        other = coerce(other)
        operand.delete(other.rename(aliases.inverse)).rename(aliases)
      end

      module Methods

        # Return a relation with the header renamed
        #
        # @example
        #   rename = relation.rename(a: :b, c: :d)
        #
        # @param [Hash, Aliases] aliases
        #   the old and new attribute names
        #
        # @return [Rename]
        #
        # @api public
        def rename(aliases)
          Rename.new(self, aliases)
        end

      end # module Methods

      Relation.class_eval { include Methods }

    end # class Rename
  end # module Algebra
end # module Axiom