Skip to content

Commit

Permalink
basic district lookup using bing and sunlight
Browse files Browse the repository at this point in the history
  • Loading branch information
turino committed Jan 29, 2015
1 parent 29077f3 commit b471e1b
Show file tree
Hide file tree
Showing 15 changed files with 297 additions and 8 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# Set development environment variables here. Uses https://github.com/bkeepers/dotenv
# S3_BUCKET=YOURS3BUCKET
# SECRET_KEY=YOURSECRETKEYGOESHERE
BING_KEY=YOURKEY
SUNLIGHT_KEY=YOURKEY
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@
/log/*
!/log/.keep
/tmp

# Ignore other unneeded files.
*.swp
*~
.DS_Store
2 changes: 2 additions & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
--color
--require spec_helper
1 change: 1 addition & 0 deletions .ruby-gemset
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mayday-2.0
1 change: 1 addition & 0 deletions .ruby-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ruby-2.2.0
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
mayone-2.0
mayday-2.0
==========

The API-driven next-generation MADAY site
The API-driven next-generation MAYDAY site

Overview
--------

This is currently an out-of-the-box [Rails 4.2](http://rubyonrails.org/) app. It uses a [PostgreSQL](http://www.postgresql.org/) database.
This is a [Rails 4.2](http://rubyonrails.org/) app. It uses a [PostgreSQL](http://www.postgresql.org/) database.

It is currently deployed on [Heroku](https://www.heroku.com/) in two environments:
This is currently deployed on [Heroku](https://www.heroku.com/) in two environments:

- **Staging** https://mayone-staging.herokuapp.com/
- **Production** https://mayone-prod.herokuapp.com/
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
class ApplicationController < ActionController::API
protect_from_forgery with: :null_session

end
2 changes: 1 addition & 1 deletion app/controllers/v1/base_controller.rb
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
class v1::BaseController < ApplicationController
class V1::BaseController < ApplicationController
end
66 changes: 66 additions & 0 deletions app/controllers/v1/congressional_district_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
class V1::CongressionalDistrictController < V1::BaseController
def index
output = {}
if address = params[:address].presence
if results = coords_from_address(address)
address_name = results[:address_name]
coords = results[:coordinates]

output = { address: address_name }.merge(district_from_coords(*coords))
else
output = { error: "couldn't find address" }
end
end

render json: output
end

private
def district_from_coords(lat, long)
key = ENV['SUNLIGHT_KEY']
url = "https://congress.api.sunlightfoundation.com/legislators/locate?latitude=#{lat}&longitude=#{long}&apikey=#{key}"
response = open(url).read
results = JSON.parse(response)['results']

return { district: 'not found' } unless results.any?

representative, senator_senior, senator_junior = [nil, nil, nil]
results.each do |person|
if person['chamber'] == 'house'
representative = person
elsif person['chamber'] == 'senate'
if person['state_rank'] == 'senior'
senator_senior = person
elsif person['state_rank'] == 'junior'
senator_junior = person
end
end
end

{ district: representative['district'],
legislators: { representative: representative,
senator_senior: senator_senior,
senator_junior: senator_junior } }

rescue OpenURI::HTTPError => e
byebug
end

def coords_from_address(address)
key = ENV['BING_KEY']
url = "http://dev.virtualearth.net/REST/v1/Locations?key=#{key}&q=#{address}"
response = open(url).read
result = JSON.parse(response)

if resource = result['resourceSets'].first['resources'].first
{ address_name: resource['name'],
coordinates: resource['point']['coordinates'],
confidence: resource['confidence'],
address: resource['address'],
type: resource['entityType'] }
end

rescue OpenURI::HTTPError => e
byebug
end
end
2 changes: 2 additions & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

require 'rails/all'

require 'open-uri'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
Expand Down
4 changes: 2 additions & 2 deletions config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Rails.application.routes.draw do
root 'welcome#index'

api_version(:module => "v1", :path => {:value => "v1"}, :default => true) do
#api routes here
resources :congressional_district, only: :index
end
end
19 changes: 19 additions & 0 deletions db/schema.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 0) do

# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"

end
56 changes: 56 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html>
<head>
<title>District Lookup</title>
<style type="text/css" media="screen">
html, body {
background-color: #4B7399;
font-family: Verdana, Helvetica, Arial;
font-size: 14px;
}

a { color: #0000FF; }

#container {
width: 75%;
margin: 0 auto;
background-color: #FFF;
padding: 20px 40px;
border: solid 1px black;
margin-top: 20px;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
$(function() {
function addPerson(person) {
$('#people').append('<li>' + person.email + '</ul>');
}

$('#address_search').submit(function(e) {
$.getJSON('/congressional_district?address=' + $('#address').val(), function(results) {
$('#address_name').html(results.address);
$('#district').html(results.district);
});
this.reset();
e.preventDefault();
});
});
</script>
</head>
<body>
<div id="container">
<h1>District Lookup</h1>
<form id="address_search">
<input type="text" name="address" id="address" size="50">
<input type="submit" value="Search">
</form>
<p>
Address: <span id="address_name"></span>
</p>
<p>
District: <span id="district"></span>
</p>
</div>
</body>
</html>
50 changes: 50 additions & 0 deletions spec/rails_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!

# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"

# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true

# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
end
85 changes: 85 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause this
# file to always be loaded, without a need to explicitly require it in any files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end

# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end

# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Limits the available syntax to the non-monkey patched syntax that is recommended.
# For more details, see:
# - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
# - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end

0 comments on commit b471e1b

Please sign in to comment.