Module: GeoKit::ActsAsMappable::ClassMethods
- Defined in:
- lib/geo_kit/acts_as_mappable.rb
Overview
Class method to mix into active record.
Instance Method Summary collapse
-
#acts_as_mappable(options = {}) ⇒ Object
Class method to bring distance query support into ActiveRecord models.
Instance Method Details
#acts_as_mappable(options = {}) ⇒ Object
Class method to bring distance query support into ActiveRecord models. By default uses :miles for distance units and performs calculations based upon the Haversine (sphere) formula. These can be changed by setting GeoKit::default_units and GeoKit::default_formula. Also, by default, uses lat, lng, and distance for respective column names. All of these can be overridden using the :default_units, :default_formula, :lat_column_name, :lng_column_name, and :distance_column_name hash keys.
Can also use to auto-geocode a specific column on create. Syntax;
acts_as_mappable :auto_geocode=>true
By default, it tries to geocode the “address” field. Or, for more customized behavior:
acts_as_mappable :auto_geocode=>{:field=>:address,:error_message=>'bad address'}
In both cases, it creates a before_validation_on_create callback to geocode the given column. For anything more customized, we recommend you forgo the auto_geocode option and create your own AR callback to handle geocoding.
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/geo_kit/acts_as_mappable.rb', line 49 def acts_as_mappable( = {}) # Mix in the module, but ensure to do so just once. return if self.included_modules.include?(GeoKit::ActsAsMappable::InstanceMethods) send :include, GeoKit::ActsAsMappable::InstanceMethods # include the Mappable module. send :include, Mappable # Handle class variables. cattr_accessor :distance_column_name, :default_units, :default_formula, :lat_column_name, :lng_column_name, :qualified_lat_column_name, :qualified_lng_column_name self.distance_column_name = [:distance_column_name] || 'distance' self.default_units = [:default_units] || GeoKit::default_units self.default_formula = [:default_formula] || GeoKit::default_formula self.lat_column_name = [:lat_column_name] || 'lat' self.lng_column_name = [:lng_column_name] || 'lng' self.qualified_lat_column_name = "#{table_name}.#{lat_column_name}" self.qualified_lng_column_name = "#{table_name}.#{lng_column_name}" if .include?(:auto_geocode) && [:auto_geocode] # if the form auto_geocode=>true is used, let the defaults take over by suppling an empty hash [:auto_geocode] = {} if [:auto_geocode] == true cattr_accessor :auto_geocode_field, :auto_geocode_error_message self.auto_geocode_field = [:auto_geocode][:field] || 'address' self. = [:auto_geocode][:error_message] || 'could not locate address' # set the actual callback here before_validation_on_create :auto_geocode_address end end |