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{ |geom| geom.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.



44
45
46
# File 'lib/rgeo/active_record/geometry_mixin.rb', line 44

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.



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

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

Instance Method Details

#as_json(opts = nil) ⇒ Object

Serializes this object as JSON for ActiveRecord.



50
51
52
# File 'lib/rgeo/active_record/geometry_mixin.rb', line 50

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