@@ -4,21 +4,55 @@ module Patches
4
4
# adds wkb/geojson conversion logic to the class it's included in
5
5
module GeojsonAttribute
6
6
7
- def geojson_additional_properties
8
- as_json except : [ :geom ]
7
+ def self . prepended ( base )
8
+ base . extend ClassMethods
9
+ base . class_eval do
10
+ scope :geojson , -> ( include_properties : false ) {
11
+ data = [ ]
12
+ where . not ( geom : nil ) .
13
+ find_in_batches . each { |group | group . each { |o |
14
+ data << o . geojson_params ( include_properties )
15
+ } }
16
+ Conversions ::WkbToJson . new . collection_to_json data
17
+ }
18
+ end
9
19
end
10
20
11
- # use simple: true to skip inclusion of record's properties
12
- def geojson ( simple : false )
13
- @geojson ||= if geom . present?
14
- Conversions . wkb_to_json (
15
- geom ,
16
- id : id ,
17
- properties : ( simple ? { } : geojson_additional_properties )
21
+ module ClassMethods
22
+ def array_to_geojson ( array , include_properties : false )
23
+ Conversions ::WkbToJson . new . collection_to_json (
24
+ array . map { |o |
25
+ o . geojson_params ( include_properties ) if o . geom
26
+ } . compact
18
27
)
19
28
end
20
29
end
21
30
31
+ def geojson_additional_properties ( include_properties = false )
32
+ case include_properties
33
+ when Hash
34
+ if only = include_properties [ :only ]
35
+ as_json only : only
36
+ else
37
+ except = include_properties [ :except ] || [ ]
38
+ except << :geom
39
+ as_json except : except
40
+ end
41
+ when TrueClass
42
+ as_json except : [ :geom ]
43
+ else
44
+ { }
45
+ end
46
+ end
47
+
48
+ # returns the geojson attribute for reading / writing to the DB
49
+ def geojson
50
+ @geojson ||= if geom . present?
51
+ Conversions . wkb_to_json geom
52
+ end
53
+ end
54
+
55
+ # sets the geojson attribute for reading / writing to the DB
22
56
def geojson = ( geometry )
23
57
@geojson = geometry
24
58
if ( geometry . present? )
@@ -28,6 +62,29 @@ def geojson=(geometry)
28
62
end
29
63
end
30
64
65
+ # returns a GeoJSON representation of this record.
66
+ #
67
+ # Use include_properties: true to include all of the record's properties
68
+ # use include_properties: { only: [ :id, :subject ] } for a specific
69
+ # subset of properties
70
+ #
71
+ # Use this method and not #geojson for rendering maps
72
+ def as_geojson ( include_properties : false )
73
+ return geojson unless include_properties
74
+
75
+ if geom . present?
76
+ Conversions . wkb_to_json (
77
+ geom ,
78
+ id : id ,
79
+ properties : geojson_additional_properties ( include_properties )
80
+ )
81
+ end
82
+ end
83
+
84
+ def geojson_params ( include_properties )
85
+ [ geom , id , geojson_additional_properties ( include_properties ) ]
86
+ end
87
+
31
88
end
32
89
end
33
90
end
0 commit comments