Class: SportDb::Reader

Inherits:
Object
  • Object
show all
Includes:
LogUtils::Logging, FixtureHelpers, Matcher, Models
Defined in:
lib/sportdb/reader.rb

Constant Summary

Constants included from Models

Models::City, Models::Continent, Models::Country, Models::Prop, Models::Region

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from FixtureHelpers

#calculate_year, #cut_off_end_of_line_comment!, #find_date!, #find_game_pos!, #find_group_title_and_pos!, #find_leading_pos!, #find_person!, #find_record_comment!, #find_record_laps!, #find_record_leading_state!, #find_record_timeline!, #find_round_pos!, #find_round_title!, #find_round_title2!, #find_scores!, #find_team!, #find_team1!, #find_team2!, #find_teams!, #find_track!, #is_group?, #is_knockout_round?, #is_postponed?, #is_round?, #map_person!, #map_team!, #map_teams!, #map_track!, #match_teams!, #match_track!

Methods included from Matcher

#match_leagues_for_country, #match_teams_for_country

Constructor Details

#initialize(include_path, opts = {}) ⇒ Reader

Returns a new instance of Reader.



33
34
35
# File 'lib/sportdb/reader.rb', line 33

def initialize( include_path, opts={})
  @include_path = include_path
end

Instance Attribute Details

#include_pathObject (readonly)

Returns the value of attribute include_path.



31
32
33
# File 'lib/sportdb/reader.rb', line 31

def include_path
  @include_path
end

Instance Method Details

#fetch_event(name) ⇒ Object



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
# File 'lib/sportdb/reader.rb', line 230

def fetch_event( name )
  # get/fetch/find event from yml file

  ## todo/fix: use h = HashFile.load( path ) or similar instead of HashReader!!

  ## todo/fix: add option for not adding prop automatically?? w/ HashReaderV2

  reader = HashReaderV2.new( name, include_path )

  event_attribs = {}

  reader.each_typed do |key, value|

    ## puts "processing event attrib >>#{key}<< >>#{value}<<..."

    if key == 'league'
      league = League.find_by_key!( value.to_s.strip )
      event_attribs[ 'league_id' ] = league.id
    elsif key == 'season'
      season = Season.find_by_key!( value.to_s.strip )
      event_attribs[ 'season_id' ] = season.id
    else
      # skip; do nothing
    end
  end # each key,value

  league_id = event_attribs['league_id']
  season_id = event_attribs['season_id']
  
  event = Event.find_by_league_id_and_season_id!( league_id, season_id )
  event
end

#fetch_event_fixtures(name) ⇒ Object



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
# File 'lib/sportdb/reader.rb', line 192

def fetch_event_fixtures( name )
  # todo: merge with fetch_event to make it single read op - why? why not??
  reader = HashReaderV2.new( name, include_path )

  fixtures = []

  reader.each_typed do |key, value|
    if key == 'fixtures' && value.kind_of?( Array )
      logger.debug "fixtures:"
      logger.debug value.to_json
      ## todo: make sure we get an array!!!!!
      fixtures = value
    else
      # skip; do nothing
    end
  end # each key,value

  if fixtures.empty?
    ## logger.warn "no fixtures found for event - >#{name}<; assume fixture name is the same as event"
    fixtures = [name]
  else
    ## add path to fixtures (use path from event e.g)
    #  - bl    + at-austria!/2012_13/bl  -> at-austria!/2012_13/bl
    #  - bl_ii + at-austria!/2012_13/bl  -> at-austria!/2012_13/bl_ii

    dir = File.dirname( name ) # use dir for fixtures

    fixtures = fixtures.map do |fx|
      fx_new = "#{dir}/#{fx}"   # add path upfront
      logger.debug "fx: #{fx_new} | >#{fx}< + >#{dir}<"
      fx_new
    end
  end

  fixtures
end

#load(name) ⇒ Object

convenience helper for all-in-one reader



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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/sportdb/reader.rb', line 50

def load( name )   # convenience helper for all-in-one reader

  logger.debug "enter load( name=>>#{name}<<, include_path=>>#{include_path}<<)"
  
  if name  =~ /^circuits/  # e.g. circuits.txt in formula1.db
    load_tracks( name )
  elsif name =~ /^drivers/ # e.g. drivers.txt in formula1.db
    load_persons( name )
  elsif name =~ /^teams/   # e.g. teams.txt in formula1.db
    load_teams( name )
  elsif name =~ /\/races/  # e.g. 2013/races.txt in formula1.db
    load_races( name )
  elsif name =~ /\/squads/ || name =~ /\/rosters/  # e.g. 2013/squads.txt in formula1.db
    load_rosters( name )
  elsif name =~ /\/([0-9]{2})-/
    race_pos = $1.to_i
    # NB: assume @event is set from previous load 
    race = Race.find_by_event_id_and_pos( @event.id, race_pos )
    load_records( name, race_id: race.id ) # e.g. 2013/04-gp-monaco.txt in formula1.db
  elsif name =~ /(?:^|\/)seasons/  # NB: ^seasons or also possible at-austria!/seasons
    load_seasons( name )
  elsif match_leagues_for_country( name ) do |country_key|  # name =~ /^([a-z]{2})\/leagues/
          # auto-add country code (from folder structure) for country-specific leagues
          #  e.g. at/leagues
          country = Country.find_by_key!( country_key )
          load_leagues( name, club: true, country_id: country.id )
        end
  elsif name =~ /(?:^|\/)leagues/   # NB: ^leagues or also possible world!/leagues  - NB: make sure goes after leagues_for_country!!
    if name =~ /-cup!?\//   # NB: -cup/ or -cup!/ 
      # e.g. national team tournaments/leagues (e.g. world-cup/ or euro-cup/)
      load_leagues( name )
    else
      # e.g. leagues_club
      load_leagues( name, club: true )
    end
  elsif match_teams_for_country( name ) do |country_key|   # name =~ /^([a-z]{2})\/teams/
          # auto-add country code (from folder structure) for country-specific teams
          #  e.g. at/teams at/teams.2 de/teams etc.                
          country = Country.find_by_key!( country_key )
          load_teams( name, club: true, country_id: country.id )
        end
  elsif name =~ /(?:^|\/)teams/
    if name =~ /-cup!?\//   # NB: -cup/ or -cup!/ 
      # assume national teams
      # e.g. world-cup/teams  amercia-cup/teams_northern
      load_teams( name, national: true )
    else
      # club teams (many countries)
      # e.g. club/europe/teams
      load_teams( name, club: true )
    end
  elsif name =~ /\/(\d{4}|\d{4}_\d{2})\// || name =~ /\/(\d{4}|\d{4}_\d{2})$/
    # e.g. must match /2012/ or /2012_13/
    #  or   /2012 or /2012_13   e.g. brazil/2012 or brazil/2012_13
    load_event( name )
    event    = fetch_event( name )
    fixtures = fetch_event_fixtures( name )
    fixtures.each do |fx|
      load_fixtures( event.key, fx )
    end
  else
    logger.error "unknown sportdb fixture type >#{name}<"
    # todo/fix: exit w/ error
  end
end

#load_event(name) ⇒ Object



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
# File 'lib/sportdb/reader.rb', line 264

def load_event( name )

####
## fix!!!!!
##   use Event.create_or_update_from_hash or similar
##   use Event.create_or_update_from_hash_reader?? or similar
#   move parsing code to model

  reader = HashReaderV2.new( name, include_path )

  event_attribs = {}
  
  ## set default sources to basename by convention
  #  e.g  2013_14/bl  => bl
  #  etc.
  # use fixtures/sources: to override default

  event_attribs[ 'sources' ] = File.basename( name )
  event_attribs[ 'config'  ] = File.basename( name )  # name a of .yml file

  reader.each_typed do |key, value|

    ## puts "processing event attrib >>#{key}<< >>#{value}<<..."

    if key == 'league'
      league = League.find_by_key( value.to_s.strip )

      ## check if it exists
      if league.present?
        event_attribs['league_id'] = league.id
      else
        logger.error "league with key >>#{value.to_s.strip}<< missing"
        exit 1
      end
     
    elsif key == 'season'
      season = Season.find_by_key( value.to_s.strip )

      ## check if it exists
      if season.present?
        event_attribs['season_id'] = season.id
      else
        logger.error "season with key >>#{value.to_s.strip}<< missing"
        exit 1
      end
      
    elsif key == 'start_at' || key == 'begin_at'
      
      if value.is_a?(DateTime) || value.is_a?(Date)
        start_at = value
      else # assume it's a string
        start_at = DateTime.strptime( value.to_s.strip, '%Y-%m-%d' )
      end
      
      event_attribs['start_at'] = start_at

    elsif key == 'end_at' || key == 'stop_at'
      
      if value.is_a?(DateTime) || value.is_a?(Date)
        end_at = value
      else # assume it's a string
        end_at = DateTime.strptime( value.to_s.strip, '%Y-%m-%d' )
      end
      
      event_attribs['end_at'] = end_at

    elsif key == 'teams'
      
      ## assume teams value is an array
      
      team_ids = []
      value.each do |item|
        team_key = item.to_s.strip
        team = Team.find_by_key!( team_key )
        team_ids << team.id
      end
      
      event_attribs['team_ids'] = team_ids
      
    elsif key == 'team3'
      ## for now always assume false  # todo: fix - use value and convert to boolean if not boolean
      event_attribs['team3'] = false
    elsif key == 'fixtures' || key == 'sources'
      if value.kind_of?(Array)
        event_attribs['sources'] = value.join(',') 
      else # assume plain (single fixture) string
        event_attribs['sources'] = value.to_s
      end
    else
      ## todo: add a source location struct to_s or similar (file, line, col)
      logger.error "unknown event attrib #{key}; skipping attrib"
    end

  end # each key,value

  league_id = event_attribs['league_id']
  season_id = event_attribs['season_id']

  logger.debug "find event - league_id: #{league_id}, season_id: #{season_id}"

  event = Event.find_by_league_id_and_season_id( league_id, season_id )

  ## check if it exists
  if event.present?
    logger.debug "*** update event #{event.id}-#{event.key}:"
  else
    logger.debug "*** create event:"
    event = Event.new
  end
  
  logger.debug event_attribs.to_json
  
  event.update_attributes!( event_attribs )

end

#load_fixtures(event_key, name) ⇒ Object

load from file system



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
# File 'lib/sportdb/reader.rb', line 395

def load_fixtures( event_key, name )  # load from file system

  ## todo: move name_real_path code to LineReaderV2 ????
  pos = name.index( '!/')
  if pos.nil?
    name_real_path = name   # not found; real path is the same as name
  else
    # cut off everything until !/ e.g.
    #   at-austria!/w-wien/beers becomes
    #   w-wien/beers
    name_real_path = name[ (pos+2)..-1 ]
  end

   
  path = "#{include_path}/#{name_real_path}.txt"

  logger.info "parsing data '#{name}' (#{path})..."
  
  SportDb.lang.lang = SportDb.lang.classify_file( path )

  reader = LineReader.new( path )
  
  load_fixtures_worker( event_key, reader )

  Prop.create_from_fixture!( name, path )
end

#load_fixtures_from_string(event_key, text) ⇒ Object

load from string (e.g. passed in via web form)



382
383
384
385
386
387
388
389
390
391
392
393
# File 'lib/sportdb/reader.rb', line 382

def load_fixtures_from_string( event_key, text )  # load from string (e.g. passed in via web form)

  SportDb.lang.lang = SportDb.lang.classify( text )

  ## todo/fix: move code into LineReader e.g. use LineReader.fromString() - why? why not?
  reader = StringLineReader.new( text )
  
  load_fixtures_worker( event_key, reader )

  ## fix add prop 
  ### Prop.create!( key: "db.#{fixture_name_to_prop_key(name)}.version", value: "file.txt.#{File.mtime(path).strftime('%Y.%m.%d')}" )  
end

#load_leagues(name, more_attribs = {}) ⇒ Object



117
118
119
120
121
122
123
124
125
# File 'lib/sportdb/reader.rb', line 117

def load_leagues( name, more_attribs={} )

  reader = ValuesReaderV2.new( name, include_path, more_attribs )

  reader.each_line do |new_attributes, values|
    League.create_or_update_from_values( new_attributes, values )
  end # each lines

end

#load_persons(name, more_attribs = {}) ⇒ Object



140
141
142
143
144
145
146
147
148
# File 'lib/sportdb/reader.rb', line 140

def load_persons( name, more_attribs={} )

  reader = ValuesReaderV2.new( name, include_path, more_attribs )

  reader.each_line do |new_attributes, values|
    Person.create_or_update_from_values( new_attributes, values )
  end # each lines

end

#load_races(name) ⇒ Object



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/sportdb/reader.rb', line 572

def load_races( name )
  load_event( name )   # must have .yml file with same name for event definition
  @event = fetch_event( name )

  logger.info "  event: #{@event.key} >>#{@event.full_title}<<"

  path = "#{include_path}/#{name}.txt"

  logger.info "parsing data '#{name}' (#{path})..."
  
  ### SportDb.lang.lang = LangChecker.new.analyze( name, include_path )

  reader = LineReader.new( path )
  
  ## for now: use all tracks (later filter/scope by event)
  @known_tracks = Track.known_tracks_table
  
  load_races_worker( reader )

  Prop.create_from_fixture!( name, path )
end

#load_races_worker(reader) ⇒ Object



595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
# File 'lib/sportdb/reader.rb', line 595

def load_races_worker( reader )

  reader.each_line do |line|
    logger.debug "  line: >#{line}<"

    cut_off_end_of_line_comment!( line )

    pos = find_leading_pos!( line )

    map_track!( line )
    track_key = find_track!( line )
    track = Track.find_by_key!( track_key )

    date      = find_date!( line )

    logger.debug "  line2: >#{line}<"

    ### check if games exists
    race = Race.find_by_event_id_and_track_id( @event.id, track.id )

    if race.present?
      logger.debug "update race #{race.id}:"
    else
      logger.debug "create race:"
      race = Race.new
    end
        
    race_attribs = {
      pos:      pos,
      track_id: track.id,
      start_at:  date,
      event_id:  @event.id
    }

    logger.debug race_attribs.to_json

    race.update_attributes!( race_attribs )
  end # lines.each

end

#load_records(name, more_attribs = {}) ⇒ Object



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# File 'lib/sportdb/reader.rb', line 424

def load_records( name, more_attribs={} )
  path = "#{include_path}/#{name}.txt"

  logger.info "parsing data '#{name}' (#{path})..."

  ### SportDb.lang.lang = LangChecker.new.analyze( name, include_path )

  reader = LineReader.new( path )

  ## for now: use all tracks (later filter/scope by event)
  # @known_tracks = Track.known_tracks_table

  ## fix: add @known_teams  - for now; use teams (not scoped by event)
  @known_teams   = TextUtils.build_title_table_for( Team.all )
  ## and for now use all persons
  @known_persons = TextUtils.build_title_table_for( Person.all )

  load_records_worker( reader, more_attribs )

  Prop.create_from_fixture!( name, path )
end

#load_records_worker(reader, more_attribs) ⇒ Object



446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/sportdb/reader.rb', line 446

def load_records_worker( reader, more_attribs )

  reader.each_line do |line|
    logger.debug "  line: >#{line}<"

    cut_off_end_of_line_comment!( line )

    state = find_record_leading_state!( line )

    map_team!( line )
    team_key = find_team!( line )
    team = Team.find_by_key!( team_key )

    map_person!( line )
    person_key = find_person!( line )
    person = Person.find_by_key!( person_key )

    timeline = find_record_timeline!( line )

    laps  = find_record_laps!( line )
    
    comment = find_record_comment!( line )

    logger.debug "  line2: >#{line}<"

    record_attribs = {
      state:  state,
      ## team_id: team.id,   ## NB: not needed for db 
      person_id: person.id,
      timeline: timeline,
      comment: comment,
      laps: laps
    }

    record_attribs = record_attribs.merge( more_attribs )

    ### check if record exists
    record = Record.find_by_race_id_and_person_id( record_attribs[ :race_id ],
                                                   record_attribs[ :person_id ])

    if record.present?
      logger.debug "update Record #{record.id}:"
    else
      logger.debug "create Record:"
      record = Record.new
    end

    logger.debug record_attribs.to_json

    record.update_attributes!( record_attribs )

  end # lines.each

end

#load_rosters(name) ⇒ Object



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
# File 'lib/sportdb/reader.rb', line 503

def load_rosters( name )
  path = "#{include_path}/#{name}.txt"

  logger.info "parsing data '#{name}' (#{path})..."

  ### SportDb.lang.lang = LangChecker.new.analyze( name, include_path )

  reader = LineReader.new( path )

  ## for now: use all tracks (later filter/scope by event)
  # @known_tracks = Track.known_tracks_table

  ## fix: add @known_teams  - for now; use teams (not scoped by event)
  ## for now use all teams
  @known_teams   = TextUtils.build_title_table_for( Team.all )
  ## and for now use all persons
  @known_persons = TextUtils.build_title_table_for( Person.all )


  load_rosters_worker( reader )

  Prop.create_from_fixture!( name, path )  
end

#load_rosters_worker(reader) ⇒ Object



527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# File 'lib/sportdb/reader.rb', line 527

def load_rosters_worker( reader )

  reader.each_line do |line|
    logger.debug "  line: >#{line}<"

    cut_off_end_of_line_comment!( line )

    pos = find_leading_pos!( line )

    map_team!( line )
    team_key = find_team!( line )
    team = Team.find_by_key!( team_key )

    map_person!( line )
    person_key = find_person!( line )
    person = Person.find_by_key!( person_key )

    logger.debug "  line2: >#{line}<"

    ### check if roster record exists
    roster = Roster.find_by_event_id_and_team_id_and_person_id( @event.id, team.id, person.id )

    if roster.present?
      logger.debug "update Roster #{roster.id}:"
    else
      logger.debug "create Roster:"
      roster = Roster.new
    end

    roster_attribs = {
      pos:       pos,
      team_id:   team.id,
      person_id: person.id,
      event_id:  @event.id   # NB: reuse/fallthrough from races - make sure load_races goes first (to setup event)
    }

    logger.debug roster_attribs.to_json

    roster.update_attributes!( roster_attribs )
  end # lines.each

end

#load_seasons(name) ⇒ Object



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
# File 'lib/sportdb/reader.rb', line 151

def load_seasons( name )

  reader = LineReaderV2.new( name, include_path )

####
## fix!!!!!
##   use Season.create_or_update_from_hash or similar
##   use Season.create_or_update_from_hash_reader?? or similar
#   move parsing code to model

  reader.each_line do |line|

    # for now assume single value
    logger.debug ">#{line}<"

    key = line

    logger.debug "  find season key: #{key}"
    season = Season.find_by_key( key )

    season_attribs = {}

    ## check if it exists
    if season.present?
      logger.debug "update season #{season.id}-#{season.key}:"
    else
      logger.debug "create season:"
      season = Season.new
      season_attribs[ :key ] = key
    end

    season_attribs[ :title ] = key # for now key n title are the same
   
    logger.debug season_attribs.to_json
        
    season.update_attributes!( season_attribs )
  end # each line

end

#load_setup(name) ⇒ Object



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

def load_setup( name )
  path = "#{include_path}/#{name}.yml"

  logger.info "parsing data '#{name}' (#{path})..."

  reader = FixtureReader.new( path )

  reader.each do |fixture_name|
    load( fixture_name )
  end
end

#load_teams(name, more_attribs = {}) ⇒ Object



637
638
639
640
641
642
643
# File 'lib/sportdb/reader.rb', line 637

def load_teams( name, more_attribs={} )
  reader = ValuesReaderV2.new( name, include_path, more_attribs )

  reader.each_line do |new_attributes, values|
    Team.create_or_update_from_values( new_attributes, values )
  end # each lines
end

#load_tracks(name, more_attribs = {}) ⇒ Object



128
129
130
131
132
133
134
135
136
# File 'lib/sportdb/reader.rb', line 128

def load_tracks( name, more_attribs={} )

  reader = ValuesReaderV2.new( name, include_path, more_attribs )

  reader.each_line do |new_attributes, values|
    Track.create_or_update_from_values( new_attributes, values )
  end # each lines

end