Sha256: 99df8beb572ec6ba54d03c1a6ea35390bb5b874149f005987ff697bb6599d8d1

Contents?: true

Size: 1.74 KB

Versions: 1

Compression:

Stored size: 1.74 KB

Contents

# frozen_string_literal: true
module GetYourRep
  # The Delegation class holds an array of Representative objects. It can enumerate on its reps.
  class Delegation
    include Enumerable
    include GetYourRep::Errors
    include GetYourRep::Associations

    # Set the reps attribute, which will hold an array of Representative objects,
    # to an empty array by default.
    #
    def initialize
      @reps = []
    end

    # Defines the enumerator methods on the :reps attribute.
    def each(&block)
      @reps.each(&block)
    end

    # Merge reps with another Delegation. This will add the reps of other to the reps of self,
    # and leave other unchanged. Only accepts a Delegation as an argument.
    def merge(other)
      if other.is_a?(self.class)
        other.reps.each { |rep| add_rep(rep) }
        self
      else
        not_a_del_error
      end
    end

    # Returns a frozen duplicate of the reps array.
    def reps
      @reps.dup.freeze
    end

    # Empties the reps array.
    def clear_reps
      @reps.clear
    end

    # Add a Representative to the reps array. Only accepts a Representative as an argument.
    def add_rep(other)
      add_child other:    other,
                model:    Representative,
                children: :reps,
                error:    -> { not_a_rep_error }
    end

    # Collects the OfficeLocations of all associated reps.
    def office_locations
      map(&:office_locations).flatten
    end

    # Collects the full names of all associated reps.
    def names
      map(&:name)
    end

    # Collects the first names of all associated reps.
    def first_names
      map(&:first_name)
    end

    # Collects the last names of all associated reps.
    def last_names
      map(&:last_name)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
get_your_rep-1.2.0 lib/get_your_rep/delegation.rb