Skip to content

Instantly share code, notes, and snippets.

@whyvez
Last active December 19, 2015 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whyvez/6011770 to your computer and use it in GitHub Desktop.
Save whyvez/6011770 to your computer and use it in GitHub Desktop.
Ruby Array extension in order to render as geoJSON using the rgeo-geojon gem

Ruby Array to_geojson

####Dependencies

####Usage Add geojson_renderer.rb file into config/initializers folder Add array.rb file in /lib/core_ext folder Add require 'core_ext/array.rb' in environment.rb

call render :geojson => @objects from controller

  • assumes id will be used for the feature id
  • assumes geom will be used for the geometry field
  • :only and :except act same as render :json => @objects

####Future add add_methods option

thanks to @beerlington for his inpiration from this post-rails-3/

class Array
def to_geojson(options={})
features = Array.new
fields = first.attributes.keys
fields -= ['id', 'geom']
fields &= options[:only].map(&:to_s) if options[:only]
fields -= options[:except].map(&:to_s) if options[:except]
self.each do |feature|
properties = Hash[fields.map {|f| [f, feature[f]]}]
features<<RGeo::GeoJSON::Feature.new(feature.geom, feature.id, {date: feature.date_time})
end
featureCollection = RGeo::GeoJSON::FeatureCollection.new(features)
RGeo::GeoJSON.encode(featureCollection).to_json
end
end
require 'action_controller/metal/renderers'
ActionController.add_renderer :geojson do |geojson, options|
self.response_body = geojson.respond_to?(:to_geojson) ? geojson.to_geojson(options) : geojson
end
@whyvez
Copy link
Author

whyvez commented Jul 16, 2013

add better error checking

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment