Class: Importer

Inherits:
Object
  • Object
show all
Defined in:
lib/bb_analytics/models/importer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv_file = nil) ⇒ Importer

Returns a new instance of Importer.



6
7
8
9
10
11
12
13
14
# File 'lib/bb_analytics/models/importer.rb', line 6

def initialize(csv_file=nil)
  if csv_file
    @csv ||= {}
    CSV.foreach(csv_file, headers: true, header_converters: :symbol, converters: :all) do |row|
      @csv[row.fields[0]] ||= []
      @csv[row.fields[0]] << Hash[row.headers[1..-1].zip(row.fields[1..-1])]
    end
  end
end

Instance Attribute Details

#csvObject

Returns the value of attribute csv.



4
5
6
# File 'lib/bb_analytics/models/importer.rb', line 4

def csv
  @csv
end

Instance Method Details

#save_baseball_playersObject



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/bb_analytics/models/importer.rb', line 16

def save_baseball_players
  @csv.keys.map do |key|
    csv[key].each do |bp|
      player = BaseballPlayer.new
      player.external_id = key
      player.birth_year  = bp[:birthyear]
      player.first_name  = bp[:namefirst]
      player.last_name   = bp[:namelast]
      player.save
      player
    end
  end
end

#save_stats_for_yearObject



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
# File 'lib/bb_analytics/models/importer.rb', line 30

def save_stats_for_year
  @csv.keys.each do |key|
    csv[key].each do |year|
      stats = StatsForYear.new
      stats.player_external_id    = key
      stats.year                  = year[:yearid]
      stats.team                  = year[:teamid]
      stats.games                 = year[:g]
      stats.at_bats               = year[:ab]
      stats.runs                  = year[:r]
      stats.hits                  = year[:h]
      stats.doubles               = year[:'2b']
      stats.triples               = year[:'3b']
      stats.home_runs             = year[:hr]
      stats.runs_batted_in        = year[:rbi]
      stats.stolen_bases          = year[:sb]
      stats.caught_stealing       = year[:cs]

      stats.calculate_batting_average!
      stats.calculate_slugging_percentage!
      stats.calculate_fantasy_points!

      stats.save if stats.year.present?
      stats
    end
  end
end