Sha256: 8c7caac84125c939c57a8bb0576fa45765e7e7650d9ecf35c9f5dc5f476579de

Contents?: true

Size: 1.85 KB

Versions: 8

Compression:

Stored size: 1.85 KB

Contents

# frozen_string_literal: true
module GetYourRep
  # Retrieve your elected state representatives from the Open States 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.
  module OpenStates
    class << self
      include GetYourRep

      # Holds the coordinates geocoded from the address. Used in the HTTP request to the API.
      attr_accessor :coordinates
      # 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

      # Initiates a chain of class method calls that will instantiate a
      # Delegation object and return it.
      def all_reps(address)
        self.coordinates = address.is_a?(Array) ? address : get_coordinates(address)
        self.response    = find_rep
        if !response || response.is_a?(String) || response.first['error']
          handle_reps_not_found_error
        else
          parse_reps
          delegation
        end
      end

      private

      # Sets parameters for and executes Open States API request.
      def find_rep
        return unless coordinates
        lat  = coordinates.first
        long = coordinates.last
        url = "http://openstates.org/api/v1/legislators/geo/?lat=#{lat}&long=#{long}"
        HTTParty.get(url).parsed_response
      end

      # Parses the JSON response and assembles it into a Delegation object.
      def parse_reps
        self.delegation = Delegation.new
        response.each do |rep|
          external_rep = OpenStatesRep.new(rep)
          rep_hash     = external_rep.build_hash
          new_rep      = Representative.new(rep_hash)
          delegation.add_rep(new_rep)
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
get_your_rep-1.2.0 lib/get_your_rep/open_states.rb
get_your_rep-1.1.1 lib/get_your_rep/open_states.rb
get_your_rep-1.1.0 lib/get_your_rep/open_states.rb
get_your_rep-1.0.8 lib/get_your_rep/open_states.rb
get_your_rep-1.0.7 lib/get_your_rep/open_states.rb
get_your_rep-1.0.6 lib/get_your_rep/open_states.rb
get_your_rep-1.0.5 lib/get_your_rep/open_states.rb
get_your_rep-1.0.4 lib/get_your_rep/open_states.rb