class NpbApi::Game

Public Class Methods

new(date: '', id: '') click to toggle source
# File lib/npb_api/game.rb, line 2
def initialize(date: '', id: '')
  @date = date
  @id = (date.year.to_s + format('%02d', date.month) + format('%02d', date.day) + id).to_i
  @doc = Nokogiri::HTML(open("http://baseball.yahoo.co.jp/npb/game/#{@id}/top"))
end

Public Instance Methods

away() click to toggle source
# File lib/npb_api/game.rb, line 8
def away
  info(:away)
end
home() click to toggle source
# File lib/npb_api/game.rb, line 12
def home
  info(:home)
end

Private Instance Methods

ballpark() click to toggle source
# File lib/npb_api/game.rb, line 76
def ballpark
  @doc.css('p.stadium').children[0].text.strip
end
datetime() click to toggle source
# File lib/npb_api/game.rb, line 71
def datetime
  hour, minute = @doc.css('p.stadium').children[2].text.split(':').map(&:to_i)
  DateTime.new(@date.year, @date.month, @date.day, hour, minute, 0, '+9')
end
home_result() click to toggle source
# File lib/npb_api/game.rb, line 66
def home_result
  return 'postponed' if status.include?('中止')

end
info(home_or_away) click to toggle source
# File lib/npb_api/game.rb, line 18
def info(home_or_away)
  {
    id: @id,
    status: status,
    team_id: team_id(home_or_away),
    score: score(home_or_away),
    result: result(home_or_away),
    datetime: datetime,
    ballpark: ballpark
  }
end
result(home_or_away) click to toggle source
# File lib/npb_api/game.rb, line 43
def result(home_or_away)
  return 'postponed' if status.include?('中止')

  case home_or_away
  when :away
    if score(:away) > score(:home)
      'win'
    elsif score(:away) < score(:home)
      'lose'
    else
      'draw'
    end
  when :home
    if score(:home) > score(:away)
      'win'
    elsif score(:home) < score(:away)
      'lose'
    else
      'draw'
    end
  end
end
score(home_or_away) click to toggle source
# File lib/npb_api/game.rb, line 34
def score(home_or_away)
  return nil if status == '試合前中止'

  case home_or_away
  when :away then @doc.css('tr#tb1 td.sum').text.to_i
  when :home then @doc.css('tr#tb2 td.sum').text.to_i
  end
end
status() click to toggle source
# File lib/npb_api/game.rb, line 30
def status
  @doc.css('.column-center em').text
end
team_id(home_or_away) click to toggle source
# File lib/npb_api/game.rb, line 80
def team_id(home_or_away)
  anchor =
    case home_or_away
    when :home then @doc.css('.column-left.clearfix a')
    when :away then @doc.css('.column-right.clearfix a')
    end
  anchor.attribute('href').value =~ /\A\/npb\/teams\/(\d+)\/\z/
  $1.to_i
end