Skip to content
This repository was archived by the owner on Jul 21, 2024. It is now read-only.

Commit 72731f5

Browse files
committed
Find user locations by IP address
I need to demonstrate testing interactions with external HTTP services. Add support for locating users based on IP addresses, and store the found location as a string on the user object. Add a dependency on the Geocoder gem to handle this.
1 parent 800569e commit 72731f5

File tree

5 files changed

+21
-1
lines changed

5 files changed

+21
-1
lines changed

Gemfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,4 @@ gem 'bootstrap-sass'
3434
gem 'jquery-rails'
3535
gem 'devise'
3636
gem 'paperclip'
37+
gem 'geocoder'

Gemfile.lock

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ GEM
8181
faker (1.7.3)
8282
i18n (~> 0.5)
8383
ffi (1.9.18)
84+
geocoder (1.4.4)
8485
globalid (0.4.0)
8586
activesupport (>= 4.2.0)
8687
i18n (0.8.1)
@@ -212,6 +213,7 @@ DEPENDENCIES
212213
coffee-rails (~> 4.2)
213214
devise
214215
faker
216+
geocoder
215217
jbuilder (~> 2.5)
216218
jquery-rails
217219
listen (>= 3.0.5, < 3.2)

app/models/user.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,17 @@ def name
1717
[first_name, last_name].join(" ")
1818
end
1919

20+
geocoded_by :last_sign_in_ip do |user, result|
21+
if !user.local? && geocode = result.first
22+
user.location = "#{geocode.city}, #{geocode.state}, #{geocode.country}"
23+
user.save
24+
end
25+
end
26+
27+
def local?
28+
["localhost", "127.0.0.1", "0.0.0.0"].include? last_sign_in_ip
29+
end
30+
2031
private
2132

2233
def ensure_authentication_token
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
class AddLocationToUsers < ActiveRecord::Migration[5.1]
2+
def change
3+
add_column :users, :location, :string
4+
end
5+
end

db/schema.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
#
1111
# It's strongly recommended that you check this file into your version control system.
1212

13-
ActiveRecord::Schema.define(version: 20170519014052) do
13+
ActiveRecord::Schema.define(version: 20170829013421) do
1414

1515
create_table "notes", force: :cascade do |t|
1616
t.text "message"
@@ -61,6 +61,7 @@
6161
t.string "first_name"
6262
t.string "last_name"
6363
t.string "authentication_token"
64+
t.string "location"
6465
t.index ["email"], name: "index_users_on_email", unique: true
6566
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
6667
end

0 commit comments

Comments
 (0)