Module: RGeo::ActiveRecord::GeometryMixin

Defined in:
lib/rgeo/active_record/geometry_mixin.rb

Overview

This module is mixed into all geometry objects. It provides an as_json method so that ActiveRecord knows how to generate JSON for a geometry-valued field.

Constant Summary collapse

DEFAULT_JSON_GENERATOR =

The default JSON generator Proc. Renders geometry fields as WKT.

Proc.new(&:to_s)

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.generate_json(geom) ⇒ Object

Given a feature, returns an object that can be serialized as JSON (i.e. usually a hash or string), using the current json_generator. This is used to generate JSON for geometry-valued ActiveRecord fields by default.



42
43
44
# File 'lib/rgeo/active_record/geometry_mixin.rb', line 42

def self.generate_json(geom)
  @json_generator.call(geom)
end

.set_json_generator(value = nil, &block) ⇒ Object

Set the style of JSON generation used for geometry fields in an ActiveRecord model by default. You may pass nil to use DEFAULT_JSON_GENERATOR, a proc that takes a geometry as the argument and returns an object that can be converted to JSON (i.e. usually a hash or string), or one of the following symbolic values:

:wkt

Well-known text format. (Same as DEFAULT_JSON_GENERATOR.)

:geojson

GeoJSON format. Requires the rgeo-geojson gem.



27
28
29
30
31
32
33
34
35
# File 'lib/rgeo/active_record/geometry_mixin.rb', line 27

def self.set_json_generator(value = nil, &block)
  if block && !value
    value = block
  elsif value == :geojson
    require "rgeo/geo_json"
    value = proc { |geom| GeoJSON.encode(geom) }
  end
  @json_generator = value.is_a?(Proc) ? value : DEFAULT_JSON_GENERATOR
end

Instance Method Details

#as_json(opts = nil) ⇒ Object

Serializes this object as JSON for ActiveRecord.



48
49
50
# File 'lib/rgeo/active_record/geometry_mixin.rb', line 48

def as_json(opts = nil)
  GeometryMixin.generate_json(self)
end