Module: DataMapper::GeoKit::ClassMethods

Defined in:
lib/dm-geokit/resource.rb

Instance Method Summary collapse

Instance Method Details

#has_geographic_location(name, options = {}) ⇒ Object Also known as: acts_as_mappable



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/dm-geokit/resource.rb', line 10

def has_geographic_location(name, options = {})
  return if self.included_modules.include?(DataMapper::GeoKit::InstanceMethods)
  send :include, InstanceMethods
  send :include, ::GeoKit::Mappable

  property name.to_sym, String, :size => 255
  property "#{name}_distance".to_sym, Float

  PROPERTY_NAMES.each do |p|
    if p.match(/l(at|ng)/)
      property "#{name}_#{p}".to_sym, Float, :precision => 15, :scale => 12, :index => true
    else
      property "#{name}_#{p}".to_sym, String, :size => 255
    end
  end

  DataMapper.auto_upgrade!

  define_method "#{name}" do
    if(value = attribute_get(name.to_sym)).nil?
      nil
    else
      GeographicLocation.new(name, self)
    end
  end

  define_method "#{name}=" do |value|
    if value.nil?
      nil
    else value.is_a?(String)
      geo = ::GeoKit::Geocoders::MultiGeocoder.geocode(value)
      if geo.success?
        attribute_set(name.to_sym, geo.full_address)
        PROPERTY_NAMES.each do |p|
          attribute_set("#{name}_#{p}".to_sym, geo.send(p.to_sym))
        end
      end
    end
  end
end