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.



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

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