Class: WeatherJp::Adapter

Inherits:
Object
  • Object
show all
Defined in:
lib/weather_jp/adapter.rb

Defined Under Namespace

Modules: Reader

Constant Summary collapse

BASE_URL =
'http://weather.service.msn.com/'
ACTION =
'data.aspx'
LANG =
'ja-JP'
SCALE =
'C'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(city_name) ⇒ Adapter

Returns a new instance of Adapter.



21
22
23
# File 'lib/weather_jp/adapter.rb', line 21

def initialize(city_name)
  @name = city_name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



19
20
21
# File 'lib/weather_jp/adapter.rb', line 19

def name
  @name
end

Class Method Details

.get(city_name) ⇒ WeatherJp::Weather?

Returns nil when not found weather forecasts.

Parameters:

  • city_name (String)

Returns:



9
10
11
# File 'lib/weather_jp/adapter.rb', line 9

def get(city_name)
  new(city_name).get
end

Instance Method Details

#build_weather(attrs, day_weathers) ⇒ Object



29
30
# File 'lib/weather_jp/adapter.rb', line 29

def build_weather(attrs, day_weathers)
end

#cityObject

Ruby 2.0.0 version has no ‘Nokogiri::XML::Element#to_h`.



48
49
50
51
52
53
# File 'lib/weather_jp/adapter.rb', line 48

def city
  @city ||= begin
    attrs = Hash[weather_node.attributes.map {|k, v| [k, v.value]}]
    City.new(attrs['weathercityname'], attrs)
  end
end

#day_weather_nodesObject



43
44
45
# File 'lib/weather_jp/adapter.rb', line 43

def day_weather_nodes
  xml.xpath('/weatherdata/weather/*[attribute::skytextday or attribute::skytext]')
end

#day_weathersObject



36
37
38
39
40
41
# File 'lib/weather_jp/adapter.rb', line 36

def day_weathers
  day_weather_nodes.each_with_index.map do |n, i|
    attrs = Hash[n.attributes.map {|k, v| [k, v.value] }]
    DayWeather.new(attrs, city, i - 1)
  end
end

#getObject



25
26
27
# File 'lib/weather_jp/adapter.rb', line 25

def get
  weather_node ? weather : nil
end

#paramsObject



71
72
73
74
75
76
77
# File 'lib/weather_jp/adapter.rb', line 71

def params
  {
    weadegreetype: SCALE,
    culture: LANG,
    weasearchstr: name,
  }
end

#urlObject



67
68
69
# File 'lib/weather_jp/adapter.rb', line 67

def url
  "#{BASE_URL}#{ACTION}?#{Rack::Utils.build_query(params)}"
end

#weatherObject



32
33
34
# File 'lib/weather_jp/adapter.rb', line 32

def weather
  Weather.new(city, day_weathers)
end

#weather_nodeObject



55
56
57
# File 'lib/weather_jp/adapter.rb', line 55

def weather_node
   @weather_node ||= xml.xpath('/weatherdata/weather').first
end

#xmlObject



59
60
61
# File 'lib/weather_jp/adapter.rb', line 59

def xml
  @xml ||= Nokogiri::XML.parse(xml_str)
end

#xml_strObject



63
64
65
# File 'lib/weather_jp/adapter.rb', line 63

def xml_str
  @xml_str ||= Reader.read(url)
end