Last active
November 15, 2022 20:42
-
-
Save heratyian/d9faf06668328c8726817076d3d4ce62 to your computer and use it in GitHub Desktop.
Serialize GeoJson using active_model_serializer and geojson_model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Serialize GeoJson using active_model_serializer and geojson_model | |
## gems | |
gem 'geojson_model' | |
gem 'active_model_serializer' | |
## Concern | |
module <Model>::GeoJsonable | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def to_geo_json(serializer:) | |
features = where(nil).map do |v| | |
properties = serializer.new(v) | |
coordinates = [v.geo_location.longitude.to_f, v.geo_location.latitude.to_f] | |
geometry = GeojsonModel::Geometry.new(type: 'Point', coordinates:) | |
GeojsonModel::Feature.new(properties:, geometry:) | |
end | |
GeojsonModel::FeatureCollection.new(features:) | |
end | |
end | |
end | |
## Model | |
class Model < Application Record | |
... | |
include GeoJsonable | |
... | |
end | |
## Controller | |
def index | |
records = Model.all | |
respond_to do |format| | |
format.geojson { render json: records.to_geo_json(serializer: MySerializer) } | |
format.json { render json: records, each_serializer: MySerializer } | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment