Module: Footballdata
- Defined in:
- lib/footballdata.rb,
lib/footballdata/mods.rb,
lib/footballdata/stat.rb,
lib/footballdata/teams.rb,
lib/footballdata/convert.rb,
lib/footballdata/leagues.rb,
lib/footballdata/download.rb,
lib/footballdata/prettyprint.rb
Defined Under Namespace
Classes: Configuration, Metal, Stat
Constant Summary collapse
- MODS =
{ 'br.1' => { 'América FC' => 'América Mineiro', # in year 2018 ?? }, 'pt.1' => { 'Vitória SC' => 'Vitória Guimarães', ## avoid easy confusion with Vitória SC <=> Vitória FC 'Vitória FC' => 'Vitória Setúbal', }, }
- TIMEZONES =
{ 'eng.1' => 'Europe/London', 'eng.2' => 'Europe/London', 'es.1' => 'Europe/Madrid', 'de.1' => 'Europe/Berlin', 'fr.1' => 'Europe/Paris', 'it.1' => 'Europe/Rome', 'nl.1' => 'Europe/Amsterdam', 'pt.1' => 'Europe/Lisbon', ## for champs default for not to cet (central european time) - why? why not? 'uefa.cl' => 'Europe/Paris', 'euro' => 'Europe/Paris', ## todo/fix - pt.1 ## one team in madeira!!! check for different timezone?? ## CD Nacional da Madeira 'br.1' => 'America/Sao_Paulo', ## todo/fix - brazil has 4 timezones ## really only two in use for clubs ## west and east (amazonas et al) ## for now use west for all - why? why not? 'copa.l' => 'America/Sao_Paulo', }
- STAGES =
map round-like to higher-level stages
{ 'REGULAR_SEASON' => ['Regular'], 'PRELIMINARY_ROUND' => ['Qualifying', 'Preliminary Round' ], 'PRELIMINARY_SEMI_FINALS' => ['Qualifying', 'Preliminary Semifinals' ], 'PRELIMINARY_FINAL' => ['Qualifying', 'Preliminary Final' ], '1ST_QUALIFYING_ROUND' => ['Qualifying', 'Qual. Round 1' ], '2ND_QUALIFYING_ROUND' => ['Qualifying', 'Qual. Round 2' ], '3RD_QUALIFYING_ROUND' => ['Qualifying', 'Qual. Round 3' ], 'QUALIFICATION_ROUND_1' => ['Qualifying', 'Qual. Round 1' ], 'QUALIFICATION_ROUND_2' => ['Qualifying', 'Qual. Round 2' ], 'QUALIFICATION_ROUND_3' => ['Qualifying', 'Qual. Round 3' ], 'ROUND_1' => ['Qualifying', 'Round 1'], ## use Qual. Round 1 - why? why not? 'ROUND_2' => ['Qualifying', 'Round 2'], 'ROUND_3' => ['Qualifying', 'Round 3'], 'PLAY_OFF_ROUND' => ['Qualifying', 'Playoff Round'], 'PLAYOFF_ROUND_1' => ['Qualifying', 'Playoff Round 1'], 'LEAGUE_STAGE' => ['League'], 'GROUP_STAGE' => ['Group'], 'PLAYOFFS' => ['Playoffs'], 'ROUND_OF_16' => ['Finals', 'Round of 16'], 'LAST_16' => ['Finals', 'Round of 16'], ## use Last 16 - why? why not? 'QUARTER_FINALS' => ['Finals', 'Quarterfinals'], 'SEMI_FINALS' => ['Finals', 'Semifinals'], 'FINAL' => ['Finals', 'Final'], }
- MAX_HEADERS =
[ 'Stage', # 0 'Group', # 1 'Matchday', # 2 'Date', # 3 'Time', # 4 'Timezone', # 5 ## move back column - why? why not? 'Team 1', # 6 'FT', # 7 'HT', # 8 'Team 2', # 9 'ET', # 10 # extra: incl. extra time 'P', # 11 # extra: incl. penalties 'Comments', # 12 'Status', # 13 / -2 # e.g. 'UTC', # 14 / -1 # date utc ]
- MIN_HEADERS =
always keep even if all empty
[ ## always keep even if all empty 'Date', 'Team 1', 'FT', 'Team 2' ]
- LEAGUES =
{ 'eng.1' => 'PL', # incl. team(s) from wales 'eng.2' => 'ELC', # PL - Premier League , England 27 seasons | 2019-08-09 - 2020-07-25 / matchday 31 # ELC - Championship , England 3 seasons | 2019-08-02 - 2020-07-22 / matchday 38 # # 2019 => 2019/20 # 2018 => 2018/19 # 2017 => xxx 2017-18 - requires subscription !!! 'es.1' => 'PD', # PD - Primera Division , Spain 27 seasons | 2019-08-16 - 2020-07-19 / matchday 31 'pt.1' => 'PPL', # PPL - Primeira Liga , Portugal 9 seasons | 2019-08-10 - 2020-07-26 / matchday 28 'de.1' => 'BL1', # BL1 - Bundesliga , Germany 24 seasons | 2019-08-16 - 2020-06-27 / matchday 34 'nl.1' => 'DED', # DED - Eredivisie , Netherlands 10 seasons | 2019-08-09 - 2020-03-08 / matchday 34 'fr.1' => 'FL1', # incl. team(s) monaco # FL1 - Ligue 1, France # 9 seasons | 2019-08-09 - 2020-05-31 / matchday 38 # # 2019 => 2019/20 # 2018 => 2018/19 # 2017 => xxx 2017-18 - requires subscription !!! 'it.1' => 'SA', # SA - Serie A , Italy 15 seasons | 2019-08-24 - 2020-08-02 / matchday 27 'br.1' => 'BSA', # BSA - Série A, Brazil # 4 seasons | 2020-05-03 - 2020-12-06 / matchday 10 # # 2020 => 2020 # 2019 => 2019 # 2018 => 2018 # 2017 => xxx 2017 - requires subscription !!! ## todo/check: use champs and NOT cl - why? why not? 'uefa.cl' => 'CL', ## note: cl is country code for chile!! - use champs - why? why not? ## was europe.cl / cl ## Copa Libertadores 'copa.l' => 'CLI', ############ ## national teams 'euro' => 'EC', 'world' => 'WC', }
Class Method Summary collapse
- .assert(cond, msg) ⇒ Object
- .config ⇒ Object
-
.configure {|config| ... } ⇒ Object
lets you use Footballdata.configure do |config| config.convert.out_dir = ‘./o’ end.
- .convert(league:, season:) ⇒ Object
- .convert_score(score) ⇒ Object
- .export_teams(league:, season:) ⇒ Object
- .fmt_competition(rec) ⇒ Object
- .fmt_count(h, sort: false) ⇒ Object
- .fmt_match(rec) ⇒ Object
- .matches(league:, season:) ⇒ Object
- .pp_matches(data) ⇒ Object
-
.schedule(league:, season:) ⇒ Object
porcelain “api”.
- .teams(league:, season:) ⇒ Object
- .vacuum(rows, headers: MAX_HEADERS, fixed_headers: MIN_HEADERS) ⇒ Object
Class Method Details
.assert(cond, msg) ⇒ Object
4 5 6 7 8 9 10 11 |
# File 'lib/footballdata/prettyprint.rb', line 4 def self.assert( cond, msg ) if cond # do nothing else puts "!!! assert failed - #{msg}" exit 1 end end |
.config ⇒ Object
29 |
# File 'lib/footballdata.rb', line 29 def self.config() @config ||= Configuration.new; end |
.configure {|config| ... } ⇒ Object
lets you use
Footballdata.configure do |config|
config.convert.out_dir = './o'
end
28 |
# File 'lib/footballdata.rb', line 28 def self.configure() yield( config ); end |
.convert(league:, season:) ⇒ Object
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 |
# File 'lib/footballdata/convert.rb', line 115 def self.convert( league:, season: ) ### note/fix: cl (champions league for now is a "special" case) # if league.downcase == 'cl' # convert_cl( league: league, # season: season ) # return # end season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) league_code = LEAGUES[league.downcase] matches_url = Metal.competition_matches_url( league_code, season.start_year ) teams_url = Metal.competition_teams_url( league_code, season.start_year ) data = Webcache.read_json( matches_url ) data_teams = Webcache.read_json( teams_url ) ## check for time zone tz_name = TIMEZONES[ league.downcase ] if tz_name.nil? puts "!! ERROR - sorry no timezone configured for league #{league}" exit 1 end tz = TZInfo::Timezone.get( tz_name ) pp tz ## build a (reverse) team lookup by name puts "#{data_teams['teams'].size} teams" teams_by_name = data_teams['teams'].reduce( {} ) do |h,rec| h[ rec['name'] ] = rec h end ## pp teams_by_name.keys mods = MODS[ league.downcase ] || {} recs = [] teams = Hash.new( 0 ) # stat = Stat.new ## track stage, match status et stats = { 'status' => Hash.new(0), 'stage' => Hash.new(0), } matches = data[ 'matches'] matches.each do |m| # stat.update( m ) ## use ? or N.N. or ? for nil - why? why not? team1 = m['homeTeam']['name'] || 'N.N.' team2 = m['awayTeam']['name'] || 'N.N.' score = m['score'] stage_key = m['stage'] stats['stage'][ stage_key ] += 1 ## track stage counts ## map stage to stage + round stage, stage_round = STAGES[ stage_key ] if stage.nil? puts "!! ERROR - no stage mapping found for stage >#{stage_key}<" exit 1 end matchday_num = m['matchday'] matchday_num = nil if matchday_num == 0 ## change 0 to nil (empty) too if stage_round.nil? ## e.g. Regular, League, Group, Playoffs ## keep/assume matchday number is matchday .e.g ## matchday 1, 2 etc. matchday = matchday_num.to_s else ## note - if matchday defined; assume leg e.g. 1|2 ## skip if different than one or two for now matchday = String.new matchday << stage_round matchday << " | Leg #{matchday_num}" if matchday_num && (matchday_num == 1 || matchday_num == 2) end group = m['group'] || '' ## GROUP_A ## shorten group to A|B|C etc. group = group.sub( /^GROUP_/, '' ) teams[ team1 ] += 1 teams[ team2 ] += 1 ### mods - rename club names unless mods.nil? || mods.empty? team1 = mods[ team1 ] if mods[ team1 ] team2 = mods[ team2 ] if mods[ team2 ] end ## auto-fix copa.l 2024 ## !! ERROR: unsupported match status >IN_PLAY< - sorry: if m['status'] == 'IN_PLAY' && team1 == 'Club Aurora' && team2 == 'FBC Melgar' m['status'] = 'FINISHED' end comments = '' ft = '' ht = '' et = '' pen = '' stats['status'][m['status']] += 1 ## track status counts case m['status'] when 'SCHEDULED', 'TIMED' ## , 'IN_PLAY' ft = '' ht = '' when 'FINISHED' ft, ht, et, pen = convert_score( score ) when 'AWARDED' assert( score['duration'] == 'REGULAR', 'score.duration REGULAR expected' ) ft = "#{score['fullTime']['home']}-#{score['fullTime']['away']}" ft << ' (*)' ht = '' comments = 'awarded' when 'CANCELLED' ## note cancelled might have scores!! -- add/fix later!!! ## ht only or ft+ht!!! (see fr 2021/22) ft = '(*)' ht = '' comments = 'canceled' ## us eng ? -> canceled, british eng. cancelled ? when 'POSTPONED' ft = '(*)' ht = '' comments = 'postponed' else puts "!! ERROR: unsupported match status >#{m['status']}< - sorry:" pp m exit 1 end ## ## add time, timezone(tz) ## 2023-08-18T18:30:00Z ## e.g. "utcDate": "2020-05-09T00:00:00Z", ## "utcDate": "2023-08-18T18:30:00Z", ## -- todo - make sure / assert it's always utc - how??? ## utc = ## tz_utc.strptime( m['utcDate'], '%Y-%m-%dT%H:%M:%SZ' ) ## note: DateTime.strptime is supposed to be unaware of timezones!!! ## use to parse utc utc = DateTime.strptime( m['utcDate'], '%Y-%m-%dT%H:%M:%SZ' ).to_time.utc assert( utc.strftime( '%Y-%m-%dT%H:%M:%SZ' ) == m['utcDate'], 'utc time mismatch' ) local = tz.to_local( utc ) ## do NOT add time if status is SCHEDULED ## or POSTPONED for now ## otherwise assume time always present - why? why not? ## todo/fix: assert matchday is a number e.g. 1,2,3, etc.!!! recs << [stage, group, matchday, local.strftime( '%Y-%m-%d' ), ['SCHEDULED','POSTPONED'].include?( m['status'] ) ? '' : local.strftime( '%H:%M' ), local.strftime( '%Z / UTC%z' ), team1, ft, ht, team2, et, pen, comments, ## add more columns e.g. utc date, status m['status'], # e.g. FINISHED, TIMED, etc. m['utcDate'], ] end # each match ## note: get season from first match ## assert - all other matches include the same season ## e.g. # "season": { # "id": 154, # "startDate": "2018-08-03", # "endDate": "2019-05-05", # "currentMatchday": 46 # } start_date = Date.strptime( matches[0]['season']['startDate'], '%Y-%m-%d' ) end_date = Date.strptime( matches[0]['season']['endDate'], '%Y-%m-%d' ) dates = "#{start_date.strftime('%b %-d')} - #{end_date.strftime('%b %-d')}" buf = '' buf << "#{season.key} (#{dates}) - " buf << "#{teams.keys.size} teams, " buf << "#{recs.size} matches" # buf << "#{stat[:regular_season][:goals]} goals" buf << "\n" puts buf =begin ## note: warn if stage is greater one and not regular season!! File.open( './errors.txt' , 'a:utf-8' ) do |f| if stat[:all][:stage].keys != ['REGULAR_SEASON'] f.write "!! WARN - league: #{league}, season: #{season.key} includes non-regular stage(s):\n" f.write " #{stat[:all][:stage].keys.inspect}\n" end end =end File.open( './logs.txt', 'a:utf-8' ) do |f| f.write "==== #{league} #{season.key} =============\n" f.write " #{stats.inspect}\n" end =begin f.write "\n================================\n" f.write "==== #{league} =============\n" f.write buf f.write " match status: #{stat[:regular_season][:status].inspect}\n" f.write " match duration: #{stat[:regular_season][:duration].inspect}\n" f.write "#{teams.keys.size} teams:\n" teams.each do |name, count| rec = teams_by_name[ name ] f.write " #{count}x #{name}" if rec f.write " | #{rec['shortName']} " if name != rec['shortName'] f.write " › #{rec['area']['name']}" f.write " - #{rec['address']}" else puts "!! ERROR - no team record found in teams.json for >#{name}<" exit 1 end f.write "\n" end end =end ## ## sort buy utc date ??? - why? why not? # recs = recs.sort { |l,r| l[1] <=> r[1] } ## reformat date / beautify e.g. Sat Aug 7 1993 recs = recs.map do |rec| rec[3] = Date.strptime( rec[3], '%Y-%m-%d' ).strftime( '%a %b %-d %Y' ) rec end ## pp recs ## check if all status colums ### are FINISHED ### if yes, set all to empty (for vacuum) if stats['status'].keys.size == 1 && stats['status'].keys[0] == 'FINISHED' recs = recs.map { |rec| rec[-2] = ''; rec } end if stats['stage'].keys.size == 1 && stats['stage'].keys[0] == 'REGULAR_SEASON' recs = recs.map { |rec| rec[0] = ''; rec } end recs, headers = vacuum( recs ) ## note: change season_key from 2019/20 to 2019-20 (for path/directory!!!!) write_csv( "#{config.convert.out_dir}/#{season.to_path}/#{league.downcase}.csv", recs, headers: headers ) teams.each do |name, count| rec = teams_by_name[ name ] print " #{count}x " print name if rec print " | #{rec['shortName']} " if name != rec['shortName'] print " › #{rec['area']['name']}" print " - #{rec['address']}" else if name == 'N.N.' ## ignore missing record else puts "!! ERROR - no team record found in teams.json for #{name}" exit 1 end end print "\n" end ## pp stat end |
.convert_score(score) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/footballdata/convert.rb', line 39 def self.convert_score( score ) ## duration: REGULAR · PENALTY_SHOOTOUT · EXTRA_TIME ft, ht, et, pen = ["","","",""] if score['duration'] == 'REGULAR' ft = "#{score['fullTime']['home']}-#{score['fullTime']['away']}" ht = "#{score['halfTime']['home']}-#{score['halfTime']['away']}" elsif score['duration'] == 'EXTRA_TIME' et = "#{score['regularTime']['home']+score['extraTime']['home']}" et << "-" et << "#{score['regularTime']['away']+score['extraTime']['away']}" ft = "#{score['regularTime']['home']}-#{score['regularTime']['away']}" ht = "#{score['halfTime']['home']}-#{score['halfTime']['away']}" elsif score['duration'] == 'PENALTY_SHOOTOUT' if score['extraTime'] ## quick & dirty hack - calc et via regulartime+extratime pen = "#{score['penalties']['home']}-#{score['penalties']['away']}" et = "#{score['regularTime']['home']+score['extraTime']['home']}" et << "-" et << "#{score['regularTime']['away']+score['extraTime']['away']}" ft = "#{score['regularTime']['home']}-#{score['regularTime']['away']}" ht = "#{score['halfTime']['home']}-#{score['halfTime']['away']}" else ### south american-style (no extra time) ## quick & dirty hacke - calc ft via fullTime-penalties pen = "#{score['penalties']['home']}-#{score['penalties']['away']}" ft = "#{score['fullTime']['home']-score['penalties']['home']}" ft << "-" ft << "#{score['fullTime']['away']-score['penalties']['away']}" ht = "#{score['halfTime']['home']}-#{score['halfTime']['away']}" end else puts "!! unknown score duration:" pp score exit 1 end [ft,ht,et,pen] end |
.export_teams(league:, season:) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/footballdata/teams.rb', line 8 def self.export_teams( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) league_code = LEAGUES[league.downcase] teams_url = Metal.competition_teams_url( league_code, season.start_year ) data_teams = Webcache.read_json( teams_url ) ## build a (reverse) team lookup by name puts "#{data_teams['teams'].size} teams" clubs = {} ## by country data_teams['teams'].each do |rec| buf = String.new ### use for string buffer (or String.new('') - why? why not? buf << "#{rec['name']}" buf << ", #{rec['founded']}" if rec['founded'] if rec['venue'] buf << ", @ #{rec['venue']}" # buf << " # #{rec['area']['name']}" end buf << "\n" alt_names = String.new alt_names << " | #{rec['shortName']}" if rec['shortName'] && rec['shortName'] != rec['name'] && rec['shortName'] != rec['tla'] alt_names << " | #{rec['tla']}" if rec['tla'] && rec['tla'] != rec['name'] if alt_names.size > 0 buf << " " buf << alt_names buf << "\n" end ## clean null in address (or keep nulls) - why? why not? ## e.g. null Rionegro null ## Calle 104 No. 13a - 32 Bogotá null buf << " address: #{rec['address'].gsub( /\bnull\b/, '')}" buf << "\n" buf << " web: #{rec['website']}" buf << "\n" buf << " colors: #{rec['clubColors']}" buf << "\n" country = rec['area']['name'] ary = clubs[ country] ||= [] ary << buf end # puts buf ## pp clubs buf = String.new if clubs.size > 1 clubs.each do |country, ary| buf << "# #{country} - #{ary.size} clubs\n" end buf << "\n" end clubs.each do |country, ary| buf << "= #{country} # #{ary.size} clubs\n\n" buf << ary.join( "\n" ) buf << "\n\n" end path = "#{config.convert.out_dir}/#{season.to_path}/#{league.downcase}.clubs.txt" write_text( path, buf ) end |
.fmt_competition(rec) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/footballdata/prettyprint.rb', line 13 def self.fmt_competition( rec ) buf = String.new buf << "==> " buf << "#{rec['competition']['name']} (#{rec['competition']['code']}) -- " buf << "#{rec['area']['name']} (#{rec['area']['code']}) " buf << "#{rec['competition']['type']} " buf << "#{rec['season']['startDate']} - #{rec['season']['endDate']} " buf << "@ #{rec['season']['currentMatchday']}" buf << "\n" buf end |
.fmt_count(h, sort: false) ⇒ Object
157 158 159 160 161 162 163 164 165 166 167 168 |
# File 'lib/footballdata/prettyprint.rb', line 157 def self.fmt_count( h, sort: false ) pairs = h.to_a if sort pairs = pairs.sort do |l,r| res = r[1] <=> l[1] ## bigger number first res = l[0] <=> r[0] if res == 0 res end end pairs = pairs.map { |name,count| "#{name} (#{count})" } pairs.join( ' · ' ) end |
.fmt_match(rec) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# File 'lib/footballdata/prettyprint.rb', line 27 def self.fmt_match( rec ) buf = String.new ## -- todo - make sure / assert it's always utc - how??? ## utc = ## tz_utc.strptime( m['utcDate'], '%Y-%m-%dT%H:%M:%SZ' ) ## note: DateTime.strptime is supposed to be unaware of timezones!!! ## use to parse utc utc = DateTime.strptime( rec['utcDate'], '%Y-%m-%dT%H:%M:%SZ' ).to_time.utc assert( utc.strftime( '%Y-%m-%dT%H:%M:%SZ' ) == rec['utcDate'], 'utc time mismatch' ) status = rec['status'] assert( %w[SCHEDULED TIMED FINISHED POSTPONED IN_PLAY ].include?( status ), "unknown status - #{status}" ) buf << '%-10s' % status buf << utc.strftime( '%a %b %d %Y %H:%M') buf << ' ' # pp rec['utcDate'] team1 = rec['homeTeam']['name'] ? "#{rec['homeTeam']['name']} (#{rec['homeTeam']['tla']})" : '?' team2 = rec['awayTeam']['name'] ? "#{rec['awayTeam']['name']} (#{rec['awayTeam']['tla']})" : '?' buf << '%22s' % team1 buf << " - " buf << '%-22s' % team2 buf << " " stage = rec['stage'] group = rec['group'] buf << "#{rec['matchday']} - #{stage} " buf << "/ #{group} " if group buf << "\n" buf << " " buf << '%-20s' % rec['score']['duration'] buf << ' '*24 duration = rec['score']['duration'] assert( %w[REGULAR EXTRA_TIME PENALTY_SHOOTOUT ].include?( duration ), "unknown duration - #{duration}" ) ft, ht, et, pen = convert_score( rec['score'] ) score = String.new if !pen.empty? if et.empty? ### south american-style (no extra time) score << "#{pen} pen. " score << "(#{ft}, #{ht})" else score << "#{pen} pen. " score << "#{et} a.e.t. " score << "(#{ft}, #{ht})" end elsif !et.empty? score << "#{et} a.e.t. " score << "(#{ft}, #{ht})" else score << "#{ft} (#{ht})" end buf << score buf << "\n" buf end |
.matches(league:, season:) ⇒ Object
17 18 19 20 21 22 23 |
# File 'lib/footballdata/download.rb', line 17 def self.matches( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) league_code = LEAGUES[ league.downcase ] puts " mapping league >#{league}< to >#{league_code}<" Metal.matches( league_code, season.start_year ) end |
.pp_matches(data) ⇒ Object
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
# File 'lib/footballdata/prettyprint.rb', line 101 def self.pp_matches( data ) ## track match status and score duration stats = { 'status' => Hash.new(0), 'duration' => Hash.new(0), 'stage' => Hash.new(0), 'group' => Hash.new(0), } first = Date.strptime( data['resultSet']['first'], '%Y-%m-%d' ) last = Date.strptime( data['resultSet']['last'], '%Y-%m-%d' ) diff = (last - first).to_i # note - returns rational number (e.g. 30/1) print "==> #{data['competition']['name']}, " print "#{first.strftime('%a %b %d %Y')} - #{last.strftime('%a %b %d %Y')}" print " (#{diff}d)" print "\n" data['matches'].each do |rec| print fmt_match( rec ) ## track stats status = rec['status'] stats['status'][status] += 1 stage = rec['stage'] stats['stage'][stage] += 1 group = rec['group'] stats['group'][group] += 1 if group duration = rec['score']['duration'] stats['duration'][duration] += 1 end print " #{data['resultSet']['played']}/#{data['resultSet']['count']} matches" print "\n" print " status (#{stats['status'].size}): " print fmt_count( stats['status'], sort: true ) print "\n" print " duration (#{stats['duration'].size}): " print fmt_count( stats['duration'], sort: true ) print "\n" print " stage (#{stats['stage'].size}): " print fmt_count( stats['stage'] ) print "\n" print " group (#{stats['group'].size}): " print fmt_count( stats['group'] ) print "\n" end |
.schedule(league:, season:) ⇒ Object
porcelain “api”
6 7 8 9 10 11 12 13 14 |
# File 'lib/footballdata/download.rb', line 6 def self.schedule( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) league_code = LEAGUES[ league.downcase ] puts " mapping league >#{league}< to >#{league_code}<" Metal.teams( league_code, season.start_year ) Metal.matches( league_code, season.start_year ) end |
.teams(league:, season:) ⇒ Object
26 27 28 29 30 31 32 |
# File 'lib/footballdata/download.rb', line 26 def self.teams( league:, season: ) season = Season( season ) ## cast (ensure) season class (NOT string, integer, etc.) league_code = LEAGUES[ league.downcase ] puts " mapping league >#{league}< to >#{league_code}<" Metal.teams( league_code, season.start_year ) end |
.vacuum(rows, headers: MAX_HEADERS, fixed_headers: MIN_HEADERS) ⇒ Object
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 |
# File 'lib/footballdata/convert.rb', line 477 def self.vacuum( rows, headers: MAX_HEADERS, fixed_headers: MIN_HEADERS ) ## check for unused columns and strip/remove counter = Array.new( MAX_HEADERS.size, 0 ) rows.each do |row| row.each_with_index do |col, idx| counter[idx] += 1 unless col.nil? || col.empty? end end ## pp counter ## check empty columns headers = [] indices = [] empty_headers = [] empty_indices = [] counter.each_with_index do |num, idx| header = MAX_HEADERS[ idx ] if num > 0 || (num == 0 && fixed_headers.include?( header )) headers << header indices << idx else empty_headers << header empty_indices << idx end end if empty_indices.size > 0 rows = rows.map do |row| row_vacuumed = [] row.each_with_index do |col, idx| ## todo/fix: use values or such?? row_vacuumed << col unless empty_indices.include?( idx ) end row_vacuumed end end [rows, headers] end |