Geokit助手的用法

Ale*_*lde 4 geokit ruby-on-rails-3

我正在尝试通过他们的IP地址本地化我的用户.正如文档所说,一个被称为类的方法geocode_ip_address已被混合到了ActionController::Base.但是必须有一些我想念的东西.我是否必须定义这样的过滤器before_filter :geocode_ip_address才能使用它?(我想知道每个请求的位置).

该文档还讨论了"首次查找将导致GeoLoc类存储在会话中:geo_location",但我当然没有在会话哈希中使用该密钥.

我究竟做错了什么?

谢谢.

小智 5

您不需要将before_filter添加到geocode_ip_address,而只需将其放在控制器中:

class YourController < ApplicationController
  geocode_ip_address

  def action
    if geo = session[:geo_location]
      # geo here is a Geokit::GeoLoc object
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

请注意,如果地理编码失败,则geo将为nil.如果您正在开发中运行,那么您将尝试对127.0.0.1进行地理编码,因此您需要在请求对象中设置remote_ip.我这样做是通过将它添加到config/environments/development.rb的底部:

class ActionDispatch::Request
  def remote_ip
    "x.x.x.x" # fill in your IP address here
  end
end
Run Code Online (Sandbox Code Playgroud)