# frozen_string_literal: true module GetYourRep # Stores rep info in key/value pairs, and makes values accessible by instance method. class Representative include GetYourRep::Errors include GetYourRep::Associations # The Delegation object that the instance belongs to. attr_reader :delegation # Rep personal attributes. attr_accessor :name, :middle_name, :office, :phones, :party, :email, :committees, :url, :photo, :twitter, :facebook, :youtube, :googleplus # Set office_locations, phones, and email as empty arrays. Set the rest of the attributes # from the options hash. def initialize(rep_hash = {}) @office_locations = [] @phones = [] @email = [] rep_hash.each do |key, val| send("#{key}=", val) end end # Returns a frozen duplicate of the office_locations array. def office_locations @office_locations.dup.freeze end # Empties the office_locations array. def clear_office_locations @office_locations.clear end # Creates a new OfficeLocation association. Sets self as the other's rep if not done so already. def add_office_location(other) add_child other: other, model: OfficeLocation, children: :office_locations, error: -> { not_an_office_error } end # Assign an individual OfficeLocation, or an array of them. def office_locations=(other) if other.is_a?(Array) other.each { |val| add_office_location(val) } else add_office_location(other) end end # Parse the first name from the :name. def first_name @first_name ||= parse_first_name end def parse_first_name if name_count == 1 nil elsif four_part_name name_array[0..-3].join(' ') else name_array[0..-2].join(' ') end end # Parse the last name from the :name. def last_name @last_name ||= parse_last_name end def parse_last_name if name_count == 1 name elsif four_part_name name_array[-2..-1].join(' ') else name_array.last end end def four_part_name (name_count > 3) || (name_array[-2].downcase == name_array[-2]) end # Splits the name into an array. def name_array @name_array ||= name.split end # Counts the elements in the name array. def name_count @name_count ||= name_array.size end # Maps the offices with the :type attribute equal to 'district'. def district_offices @district_offices ||= office_locations.select { |office| office.type == 'district' } end # Maps the offices with the :type attribute equal to 'capitol'. def capitol_offices @capitol_offices ||= office_locations.select { |office| office.type == 'capitol' } end # Displays self for the CLI. def cli_display cli_basic_info office_locations.each(&:cli_display) cli_display_committees end # Display basic info. def cli_basic_info puts name.bold.blue puts " #{office}".red puts " #{party}".red phones.each { |phone| puts " #{phone}".red } end # Display committee info. def cli_display_committees return unless committees && !committees.empty? puts ' Committees'.bold.blue committees.each { |comm| puts " #{comm}".red } end end end