Class: Cowa::WeatherHacks

Inherits:
Object
  • Object
show all
Defined in:
lib/cowa/weather_hacks.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key) ⇒ WeatherHacks

Returns a new instance of WeatherHacks.



9
10
11
12
# File 'lib/cowa/weather_hacks.rb', line 9

def initialize(api_key)
  @contentsgeocoder = Yapi::OpenLocalPlatform::ContentsGeoCoder.new(api_key)
  self.rss = xml_to_json(open(URI.encode("http://weather.livedoor.com/forecast/rss/primary_area.xml")).read)[:rss][:channel][:source][:pref]
end

Instance Attribute Details

#rssObject

Returns the value of attribute rss.



7
8
9
# File 'lib/cowa/weather_hacks.rb', line 7

def rss
  @rss
end

Instance Method Details

#client(url) ⇒ Object



68
69
70
# File 'lib/cowa/weather_hacks.rb', line 68

def client url
  return open(URI.encode(url)).read
end

#forecast(location) ⇒ Object



72
73
74
75
76
77
# File 'lib/cowa/weather_hacks.rb', line 72

def forecast location
  rss = locationToRss(location)
  return nil if rss.nil?
  req_url = "http://weather.livedoor.com/forecast/webservice/json/v1?city=#{rss}"
  return JSON.parse(client(req_url), symbolize_names: true)
end

#get_city(pref) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/cowa/weather_hacks.rb', line 48

def get_city pref
  self.rss().each do |t|
    if t[:title] == pref
      return t[:city]
    end
  end
  return nil
end

#get_id(city, location) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/cowa/weather_hacks.rb', line 57

def get_id(city, location)
  unless city.nil?
    city.each do |c|
      return c[:id] if c[:title] == location
    end
    return city[0][:id]
  else
    return nil
  end
end

#get_pref(location) ⇒ Object



42
43
44
45
46
# File 'lib/cowa/weather_hacks.rb', line 42

def get_pref location
  json = @contentsgeocoder.contentsGeoCoder(location)
  return nil if json[:YDF][:ResultInfo][:Count] == "0"
  return json[:YDF][:Feature][:Property][:AddressElement]
end

#locationToRss(location) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/cowa/weather_hacks.rb', line 19

def locationToRss location
  pref = get_pref location
  return nil if pref.nil?
  if pref[0][:Name] == "北海道"
    if location == "北海道"
      return self.rss[3][:city][0][:id]
    end
    for i in 0..4
      self.rss[i][:city].each do |c|
        return c[:id] if pref[1][:Name].include?(c[:title])
      end
    end
    return nil
  end
  unless pref.nil?
    city = get_city pref[0][:Name]
  else
    city = get_city location
  end
  id = get_id(city, location)
  return id
end

#xml_to_json(xml) ⇒ Object



14
15
16
17
# File 'lib/cowa/weather_hacks.rb', line 14

def xml_to_json xml
  doc = Hash.from_xml xml
  return JSON.parse(doc.to_json, symbolize_names: true)
end