Commit ea86df6

mo khan <mo@mokhan.ca>
2016-04-30 04:42:27
assign lat/long before save.
1 parent 808e0e0
Changed files (3)
app/models/gym.rb
@@ -1,5 +1,12 @@
 class Gym < ActiveRecord::Base
-  def self.closest_to(user)
-    all
+  validates_presence_of :name
+  before_save :assign_location
+
+  scope :closest_to, ->(user) { all }
+
+  private
+
+  def assign_location
+    self.latitude, self.longitude = Location.from(address, city, state, country)
   end
 end
app/models/location.rb
@@ -0,0 +1,4 @@
+class Location
+  def self.from(address, city, state, country)
+  end
+end
spec/models/gym_spec.rb
@@ -0,0 +1,33 @@
+require 'rails_helper'
+
+describe Gym do
+  subject { build(:gym) }
+
+  describe "#validations" do
+    it 'validates the presence of name' do
+      subject.name = nil
+      expect(subject).to be_invalid
+      expect(subject.errors[:name]).to be_present
+    end
+  end
+
+  describe "#before_save" do
+    let(:latitude) { rand(90.0) }
+    let(:longitude) { rand(180.0) }
+
+    it 'updates the latitude/logitude' do
+      allow(Location).to receive(:from).and_return([latitude, longitude])
+      subject.assign_attributes(
+        address: '123 street sw',
+        city: 'edmonton',
+        state: 'alberta',
+        country: 'canada',
+      )
+      subject.save!
+      subject.reload
+
+      expect(subject.latitude).to eql(latitude)
+      expect(subject.longitude).to eql(longitude)
+    end
+  end
+end