Add Google Map of voters
[selectricity-live] / vendor / plugins / geokit / lib / geo_kit / ip_geocode_lookup.rb
1 require 'yaml'
2
3 module GeoKit 
4   # Contains a class method geocode_ip_address which can be used to enable automatic geocoding
5   # for request IP addresses.  The geocoded information is stored in a cookie and in the 
6   # session to minimize web service calls.  The point of the helper is to enable location-based
7   # websites to have a best-guess for new visitors.
8   module IpGeocodeLookup
9     # Mix below class methods into ActionController.
10     def self.included(base) # :nodoc:
11       base.extend ClassMethods
12     end
13     
14     # Class method to mix into active record.
15     module ClassMethods # :nodoc:
16       def geocode_ip_address(filter_options = {})
17         before_filter :store_ip_location
18       end
19     end
20  
21     private   
22          
23     # Places the IP address' geocode location into the session if it 
24     # can be found.  Otherwise, looks for a geo location cookie and
25     # uses that value.  The last resort is to call the web service to
26     # get the value.
27     def store_ip_location
28       session[:geo_location] ||= retrieve_location_from_cookie_or_service
29       cookies[:geo_location] = { :value => session[:geo_location].to_yaml, :expires => 30.days.from_now } if session[:geo_location]
30     end    
31     
32     # Uses the stored location value from the cookie if it exists.  If
33     # no cookie exists, calls out to the web service to get the location. 
34     def retrieve_location_from_cookie_or_service
35       return YAML.load(cookies[:geo_location]) if cookies[:geo_location]
36       location = Geocoders::IpGeocoder.geocode(get_ip_address)
37       return location.success ? location : nil
38     end
39     
40     # Returns the real ip address, though this could be the localhost ip
41     # address.  No special handling here anymore.
42     def get_ip_address
43       request.remote_ip
44     end
45   end
46 end

Benjamin Mako Hill || Want to submit a patch?