Skip to content

Commit

Permalink
Add task to backfill location polygons centroid
Browse files Browse the repository at this point in the history
The task will calculate and populate the centroid of the location
polygons with an area but not stored centroid info.
  • Loading branch information
scruti committed Jan 23, 2025
1 parent 42e08e9 commit 2f6b796
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/tasks/backfill_location_polygons_centroid.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace :location_polygons do
desc "Computes and set centroid on location polygons containing an area but no centroid"
task backfill_centroid: :environment do
LocationPolygon.where.not(area: nil).where(centroid: nil).update_all("centroid = ST_Centroid(area)")
end
end
1 change: 1 addition & 0 deletions spec/factories/location_polygons.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
name { "London" }
location_type { "cities" }
area { "POLYGON((0 0, 1 1, 0 1, 0 0))" }
centroid { "POINT(0.33331264776372055 0.6666929898148579)" }
end
end
26 changes: 26 additions & 0 deletions spec/tasks/backfill_location_polygons_centroid_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
require "rails_helper"

RSpec.describe "location_polygons:backfill_centroid" do
let(:area) { "POLYGON((0 0, 1 1, 0 1, 0 0))" }
let(:centroid) { "POINT(0.33331264776372055 0.6666929898148579)" }

it "computes and sets the centroid on location polygons containing an area but no centroid" do
location_polygon = create(:location_polygon, area: area, centroid: nil)

expect { task.invoke }.to change { location_polygon.reload.centroid }.from(nil).to(
RGeo::Geographic.spherical_factory(srid: 4326).parse_wkt(centroid),
)
end

it "does not update the centroid if it is already set" do
location_polygon = create(:location_polygon, area: area, centroid: centroid)

expect { task.invoke }.not_to(change { location_polygon.reload.centroid })
end

it "does not update the centroid if the area is nil" do
location_polygon = create(:location_polygon, area: nil, centroid: nil)

expect { task.invoke }.not_to(change { location_polygon.reload.centroid })
end
end

0 comments on commit 2f6b796

Please sign in to comment.