Commit 929da75
Changed files (4)
app
models
views
gyms
spec
models
app/models/gym.rb
@@ -1,8 +1,9 @@
class Gym < ActiveRecord::Base
validates_presence_of :name
- has_one :location, as: :locatable
+ has_one :location, as: :locatable, dependent: :destroy
accepts_nested_attributes_for :location
acts_as_mappable through: :location
+ delegate :full_address, to: :location, allow_nil: true
scope :closest_to, ->(location, distance: 100) do
if location.present? && location.coordinates.present?
@@ -56,7 +57,12 @@ class Gym < ActiveRecord::Base
end
end
- def full_address
- "#{location.try(:address)}, #{location.try(:city)}, #{location.try(:region)}, #{location.try(:country)}"
+ def duplicate?
+ Gym.
+ within(1, units: :kms, origin: location.coordinates).
+ joins(:location).
+ where.not(id: id).
+ limit(1).
+ any?
end
end
app/models/location.rb
@@ -6,6 +6,10 @@ class Location < ActiveRecord::Base
lat_column_name: :latitude,
lng_column_name: :longitude
+ def full_address
+ "#{try(:address)}, #{try(:city)}, #{try(:region)}, #{try(:country)}"
+ end
+
def coordinates
latitude == 0.0 && longitude == 0.0 ? [] : [latitude, longitude]
end
app/views/gyms/_index.html.erb
@@ -16,7 +16,7 @@
<% end %>
</td>
<td>
- <% if gym.new_record? %>
+ <% if gym.new_record? && !gym.duplicate? %>
<%= form_for(gym) do |form| %>
<%= form.hidden_field :name %>
<%= form.fields_for :location do |location_form| %>
spec/models/gym_spec.rb
@@ -104,4 +104,33 @@ describe Gym do
).map(&:name)).to match_array(["Sait Campus Centre"])
end
end
+
+ describe "#full_address" do
+ let(:location) { build(:location) }
+
+ it 'returns the full address' do
+ subject.location = location
+ expected = "#{location.address}, " +
+ "#{location.city}, " +
+ "#{location.region}, " +
+ "#{location.country}"
+ expect(subject.full_address).to eql(expected)
+ end
+ end
+
+ describe "#duplicate?" do
+ it 'returns true when a dup is found' do
+ subject.location = create(:portland)
+ subject.save!
+ other = create(:gym, location: create(:portland))
+
+ expect(subject.duplicate?).to be_truthy
+ end
+
+ it 'returns false when no dups are found' do
+ subject.location = create(:portland)
+ subject.save!
+ expect(subject.duplicate?).to be_falsey
+ end
+ end
end