Commit 1752898

mo khan <mo@mokhan.ca>
2016-05-01 18:56:25
implement ip lookup.
1 parent b2f4d2b
Changed files (2)
app
spec
app/models/location.rb
@@ -2,6 +2,16 @@ class Location < ActiveRecord::Base
   before_save :assign_coordinates
 
   def self.build_from_ip(ip)
+    result = Geocoder.search(ip).first
+    new(
+      address: result.address,
+      city: result.city,
+      region: result.state_code,
+      country: result.country_code,
+      postal_code: result.postal_code,
+      latitude: result.latitude,
+      longitude: result.longitude,
+    )
   end
 
   def self.from(address, city, region, country)
@@ -12,6 +22,7 @@ class Location < ActiveRecord::Base
   private
 
   def assign_coordinates
+    return if self.latitude.present? || self.longitude.present?
     self.latitude, self.longitude = Location.from(address, city, region, country)
   end
 end
spec/models/location_spec.rb
@@ -30,4 +30,23 @@ describe Location do
       expect(location.longitude).to eql(longitude)
     end
   end
+
+  describe ".build_from_ip" do
+    it 'returns a location from the ip address' do
+      result = Location.build_from_ip("70.173.137.232")
+      expect(result).to be_instance_of(Location)
+      expect(result.address).to include("Las Vegas")
+      expect(result.city).to eql("Las Vegas")
+      expect(result.region).to eql("NV")
+      expect(result.country).to eql("US")
+      expect(result.postal_code).to eql("89101")
+      expect(result.latitude).to be_within(0.1).of(36.1)
+      expect(result.longitude).to be_within(0.1).of(-115.1)
+    end
+
+    it 'returns a location from the ip address' do
+      result = Location.build_from_ip("127.0.0.1")
+      expect(result).to be_instance_of(Location)
+    end
+  end
 end