Module: ActsAsGeocodable::Model::ClassMethods

Defined in:
lib/acts_as_geocodable.rb

Instance Method Summary collapse

Instance Method Details

#farthestObject

Find the farthest location to the given origin

Model.origin("Grand Rapids, MI").farthest


118
119
120
# File 'lib/acts_as_geocodable.rb', line 118

def farthest
  far.first
end

#location_to_geocode(location) ⇒ Object

Convert the given location to a Geocode



123
124
125
126
127
128
129
# File 'lib/acts_as_geocodable.rb', line 123

def location_to_geocode(location)
  case location
  when Geocode then location
  when InstanceMethods then location.geocode
  when String, Fixnum then Geocode.find_or_create_by_query(location.to_s)
  end
end

#nearestObject

Find the nearest location to the given origin

Model.origin("Grand Rapids, MI").nearest


110
111
112
# File 'lib/acts_as_geocodable.rb', line 110

def nearest
  near.first
end

#validates_as_geocodable(options = {}) ⇒ Object

Validate that the model can be geocoded

Options:

  • :message: Added to errors base (Default: Address could not be geocoded.)

  • :allow_nil: If all the address attributes are blank, then don’t try to validate the geocode (Default: false)

  • :precision: Require a minimum geocoding precision

validates_as_geocodable also takes a block that you can use to performa additional checks on the geocode. If this block returns false, then validation will fail.

validates_as_geocodable do |geocode|
  geocode.country == "US"
end


146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/acts_as_geocodable.rb', line 146

def validates_as_geocodable(options = {})
  options = options.reverse_merge :message => "Address could not be geocoded.", :allow_nil => false
  validate do |model|
    is_blank = model.to_location.attributes.except(:precision).all?(&:blank?)
    unless options[:allow_nil] && is_blank
      geocode = model.send :attach_geocode
      if !geocode ||
          (options[:precision] && geocode.precision < options[:precision]) ||
          (block_given? && yield(geocode) == false)
        model.errors.add :base, options[:message]
      end
    end
  end
end