Module: BaseballStats::Import

Extended by:
Import
Included in:
BaseballStats, Import
Defined in:
lib/baseball_stats/import.rb

Constant Summary collapse

SEED_BATTINGS_CSV =
File.expand_path('../../../sample_data/battings.csv', __FILE__)
SEED_PLAYERS_CSV =
File.expand_path('../../../sample_data/players.csv', __FILE__)

Instance Method Summary collapse

Instance Method Details

#import_battings_from_csv(csv_file) ⇒ Object



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
# File 'lib/baseball_stats/import.rb', line 21

def import_battings_from_csv(csv_file)
  CreateBattings.up unless ActiveRecord::Base.connection.table_exists?('battings')
  CSV.foreach(csv_file, headers: true, header_converters: :symbol) do |batting|
    new_batting                       = BaseballStats::Batting.find_or_create_by(
      player_id: batting[:player_id],
      year_id: batting[:year_id],
      league: batting[:league],
      team_id: batting[:team_id]
    )

    new_batting.league                = batting[:league]
    new_batting.team_id               = batting[:team_id]
    new_batting.appearances           = batting[:appearances]
    new_batting.at_bats               = batting[:at_bats]
    new_batting.runs_scored           = batting[:runs_scored]
    new_batting.hits                  = batting[:hits]
    new_batting.doubles               = batting[:doubles]
    new_batting.triples               = batting[:triples]
    new_batting.home_runs             = batting[:home_runs]
    new_batting.runs_batted_in        = batting[:runs_batted_in]
    new_batting.stolen_bases          = batting[:stolen_bases]
    new_batting.times_caught_stealing = batting[:times_caught_stealing]
    new_batting.save!
  end
end

#import_players_from_csv(csv_file) ⇒ Object



47
48
49
50
51
52
53
54
55
56
# File 'lib/baseball_stats/import.rb', line 47

def import_players_from_csv(csv_file)
  CreatePlayers.up unless ActiveRecord::Base.connection.table_exists?('players')
  CSV.foreach(csv_file, headers: true, header_converters: :symbol) do |player|
    new_player            = BaseballStats::Player.find_or_create_by(player_id: player[:player_id])
    new_player.birth_year = player[:birth_year]
    new_player.first_name = player[:name_first]
    new_player.last_name  = player[:name_last]
    new_player.save!
  end
end

#seed_dataObject



16
17
18
19
# File 'lib/baseball_stats/import.rb', line 16

def seed_data
  import_players_from_csv(SEED_PLAYERS_CSV)
  import_battings_from_csv(SEED_BATTINGS_CSV)
end