# frozen_string_literal: true module GetYourRep # Retrieve your elected representatives from the Google Civic Information API, parse it from # JSON, and assemble it into a usable Ruby Hash-like object called a Representative. # Representatives are then wrapped in an Array-like object called a Delegation. # # You must configure your own Google API key as an environment variable using the constant name # 'GOOGLE_API_KEY' in order for this gem to work. module Google class << self include GetYourRep # Holds the parsed address for the HTTP request. attr_accessor :address # Holds the Delegation object which will be returned by the all_reps class method. attr_accessor :delegation # Holds the raw JSON data response from the API. attr_accessor :response # The Google API key is used to access data from the Google Civic Information API. You must # obtain your own and configure it as an environment variable on your system. API_KEY = ENV['GOOGLE_API_KEY'] # Makes the call to the Google API and delivers the response after parsing. # Returns a GetYourRep::Delegation object, holding a collection of GetYourRep::Representatives def all_reps(address, congress_only: nil) init(address) ask_google_api(congress_only: congress_only) deliver_response end private def init(address) address = convert_zip_to_address(address) if address_is_a_zip?(address) self.address = parse_address(address) end def ask_google_api(congress_only: nil) url = congress_only ? congress_only_url : all_reps_url self.response = HTTParty.get(url).parsed_response end def all_reps_url # rubocop:disable Style/StringLiterals "https://www.googleapis.com/civicinfo/v2/representatives?address=#{address}%20&"\ "includeOffices=true&levels=country&levels=administrativeArea1&roles=legislatorLower"\ "Body&roles=legislatorUpperBody&roles=headOfGovernment&roles=deputyHeadOfGovernment&"\ "fields=offices%2Cofficials&key=#{API_KEY}" end def congress_only_url "https://www.googleapis.com/civicinfo/v2/representatives?address=#{address}%20&"\ "includeOffices=true&levels=country&roles=legislatorLowerBody&roles=legislatorUpper"\ "Body&fields=offices%2Cofficials&key=#{API_KEY}" end # rubocop:enable Style/StringLiterals def deliver_response if response.empty? || response['error'] handle_reps_not_found_error else parse_reps delegation end end def parse_reps self.delegation = Delegation.new response['officials'].each_with_index do |official, index| external_rep = GoogleRep.new(official) rep_hash = external_rep.build_hash(response['offices'], index) new_rep = Representative.new(rep_hash) delegation.add_rep(new_rep) end end end end end