Module: KansaiTrainInfo

Defined in:
lib/kansai_train_info.rb,
lib/kansai_train_info/cli.rb,
lib/kansai_train_info/client.rb,
lib/kansai_train_info/version.rb

Defined Under Namespace

Classes: CLI

Constant Summary collapse

LINES =
{
  大阪環状線: [4, 2, 263],
  近鉄京都線: [6, 5, 288],
  阪急京都線: [8, 2, 306],
  御堂筋線: [10, 3, 321],
  烏丸線: [34, 2, 318],
  東西線: [34, 3, 319]
}.freeze
VERSION =
'0.2.1'

Class Method Summary collapse

Class Method Details

.description(detail_url) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/kansai_train_info/client.rb', line 49

def description(detail_url)
  charset = nil
  detail_html = URI.open(detail_url) do |f|
    charset = f.charset
    f.read
  end
  detail_doc = Nokogiri::HTML.parse(detail_html, nil, charset)
  detail_doc.xpath('//*[@id="mdServiceStatus"]/dl/dd/p').first.text
end

.get(route_array, url: false) ⇒ Object

rubocop:disable Metrics/AbcSize, Layout/LineLength



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/kansai_train_info/client.rb', line 17

def get(route_array, url: false)
  messages = []

  route_array.each do |route|
    line = LINES[route.to_sym]
    raise KeyError, "Invalid route: #{route}" unless line

    status_xpath = "//*[@id='mdAreaMajorLine']/div[#{LINES[route.to_sym][0]}]/table/tr[#{LINES[route.to_sym][1]}]/td[2]"
    detail_url = "https://transit.yahoo.co.jp/traininfo/detail/#{LINES[route.to_sym][2]}/0/"
    state = kansai_doc.xpath(status_xpath).first&.text
    messages << message(route, state, url, detail_url)
  end
  if messages.empty?
    puts '利用可能な路線を入力してください'
  else
    messages.join(', ')
  end
end

.helpObject

rubocop:enable Metrics/CyclomaticComplexity



79
80
81
82
# File 'lib/kansai_train_info/client.rb', line 79

def help
  help_message = "利用可能な路線:\n大阪環状線、近鉄京都線、阪急京都線, 御堂筋線, 烏丸線, 東西線"
  puts help_message
end

.kansai_docObject

rubocop:enable Metrics/AbcSize, Layout/LineLength



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/kansai_train_info/client.rb', line 37

def kansai_doc
  charset = nil
  url = 'https://transit.yahoo.co.jp/traininfo/area/6/'

  html = URI.open(url) do |f|
    charset = f.charset
    f.read
  end

  Nokogiri::HTML.parse(html, nil, charset)
end

.message(route, state, url, detail_url) ⇒ Object

rubocop:disable Metrics/CyclomaticComplexity



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/kansai_train_info/client.rb', line 60

def message(route, state, url, detail_url)
  return "#{route}は運行情報がありません" if state.nil?

  state&.slice!('[○]')
  state&.slice!('[!]')
  puts "#{route}#{state}です" if state == '平常運転'
  message = case state
            when '運転状況'
              "#{route}#{state}に変更があります。"
            when '列車遅延'
              "#{route}#{state}があります。"
            when '運転見合わせ'
              "#{route}#{state}しています。"
            end
  show_message = "#{message} #{description(detail_url)}"
  url ? show_message + detail_url : show_message
end