2015-08-10 2 views
2

Я пытаюсь кэшировать ответ метеоролог (в https://github.com/dlt/yahoo_weatherman) в Memcache, чтобы избежать выборки погоды несколько раз, я делаю:Как кэшировать Погода (Nokogiri :: XML :: Объект NodeSet) в Memcache?

weather = Rails.cache.fetch([:weather_by_woeid, weather.woeid], expires_in: 1.hour) do 
    client = Weatherman::Client.new 
    client.lookup_by_woeid weather.woeid 
    end 

Однако я получаю это исключение:

ERROR -- : Marshalling error for key 'Timeline:weather_by_woeid/26352062': no _dump_data is defined for class Nokogiri::XML::NodeSet 
ERROR -- : You are trying to cache a Ruby object which cannot be serialized to memcached. 
ERROR -- : /var/lib/gems/2.2.0/gems/dalli-2.7.4/lib/dalli/server.rb:402:in `dump' 

Что такое лучший способ справиться с этим?

ответ

3

Это невозможно с данным кодом базы yahoo_weatherman.

Причина заключается в том, что Response из yahoo_weatherman жемчужину инкапсулирует ответ XML в виде Nokogiri::XML::NodeSet, который не может быть сериализации, и, следовательно, не может быть в кэше.

Чтобы обойти эту проблему, мы можем обезопасить класс Weathernan::Client, чтобы мы получили доступ к необработанному ответу API Weatherman, который является строкой и может быть кэширован.

# Extends the default implementation by a method that can give us raw response 
class Weatherman::Client 
    def lookup_raw_by_woeid(woeid) 
     raw = get request_url(woeid) 
    end 
end 

# We call the lookup_raw_by_woeid and cache its response (string) 
weather = Rails.cache.fetch([:weather_by_woeid, weather.woeid], expires_in: 1.hour) do 
    client = Weatherman::Client.new 
    client.lookup_raw_by_woeid weather.woeid 
end 

# We now convert that string into a Weatherman response. 
w = Weatherman::Response.new(weather) 

# Print some values from weather response 
p w.wind 
Смежные вопросы