Commit d456b6c

mo khan <mo@mokhan.ca>
2016-05-01 20:54:51
load all gyms when location of user is unknown.
1 parent 324972a
app/models/gym.rb
@@ -4,9 +4,10 @@ class Gym < ActiveRecord::Base
   accepts_nested_attributes_for :location
   acts_as_mappable through: :location
 
-  scope :closest_to, ->(location) do
-    if location.present?
-      joins(:location).within(100, units: :kms, origin: location.coordinates)
+  scope :closest_to, ->(location, distance: 100) do
+    if location.present? && location.coordinates.present?
+      joins(:location).
+        within(distance, units: :kms, origin: location.coordinates)
     else
       all
     end
app/models/location.rb
@@ -7,7 +7,7 @@ class Location < ActiveRecord::Base
     lng_column_name: :longitude
 
   def coordinates
-    [latitude, longitude]
+    latitude == 0.0 && longitude == 0.0 ? [] : [latitude, longitude]
   end
 
   class << self
app/views/gyms/index.html.erb
@@ -9,8 +9,8 @@
       <% @gyms.each do |gym| %>
         <tr>
         <td><%= gym.name %></td>
-        <td><%= gym.address %>, <%= gym.city %>, <%= gym.state %>, <%= gym.country %></td>
-        <td><a href="https://maps.google.com/?q=<%= gym.latitude %>,<%= gym.longitude %>" target="_blank"><%= t('.view_map') %></a></td>
+        <td><%= gym.location.address %>, <%= gym.location.city %>, <%= gym.location.region %>, <%= gym.location.country %></td>
+        <td><a href="https://maps.google.com/?q=<%= gym.location.latitude %>,<%= gym.location.longitude %>" target="_blank"><%= t('.view_map') %></a></td>
       </tr>
     <% end %>
     </table>
spec/models/gym_spec.rb
@@ -43,5 +43,10 @@ describe Gym do
       results = Gym.closest_to(nil)
       expect(results).to match_array([calgary_gym, edmonton_gym])
     end
+
+    it 'returns all the gym when coordinates are empty' do
+      results = Gym.closest_to(build(:no_where))
+      expect(results).to match_array([calgary_gym, edmonton_gym])
+    end
   end
 end
spec/models/location_spec.rb
@@ -49,4 +49,19 @@ describe Location do
       expect(result).to be_instance_of(Location)
     end
   end
+
+  describe "#coordinates" do
+    it 'returns the lat/long' do
+      subject.latitude, subject.longitude = rand(90.0), rand(180.0)
+      expect(subject.coordinates).to eql([
+        subject.latitude,
+        subject.longitude
+      ])
+    end
+
+    it 'returns an empty array' do
+      subject = Location.build_from_ip("172.18.0.1")
+      expect(subject.coordinates).to be_empty
+    end
+  end
 end
spec/factories.rb
@@ -87,5 +87,13 @@ FactoryGirl.define do
       region { "AB" }
       country { "CA" }
     end
+    factory :no_where do
+      latitude { 0.0 }
+      longitude { 0.0 }
+      city { "" }
+      region { "" }
+      country { "" }
+      postal_code { "" }
+    end
   end
 end