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.
9 # Mix below class methods into ActionController.
10 def self.included(base) # :nodoc:
11 base.extend ClassMethods
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
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
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]
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
40 # Returns the real ip address, though this could be the localhost ip
41 # address. No special handling here anymore.