Class: BStats::PlayerBattingStat
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- BStats::PlayerBattingStat
- Defined in:
- lib/bstats/player_batting_stat.rb
Class Method Summary collapse
- .calculate_batting_average(hits, at_bats) ⇒ Object
- .calculate_slugging_percentage(hits, doubles, triples, home_runs, at_bats) ⇒ Object
- .import_csv(file) ⇒ Object
Class Method Details
.calculate_batting_average(hits, at_bats) ⇒ Object
39 40 41 |
# File 'lib/bstats/player_batting_stat.rb', line 39 def self.calculate_batting_average(hits, at_bats) [0, "0", ""].include?(at_bats) ? 0 : (hits.to_f / at_bats.to_f).round(3) end |
.calculate_slugging_percentage(hits, doubles, triples, home_runs, at_bats) ⇒ Object
43 44 45 |
# File 'lib/bstats/player_batting_stat.rb', line 43 def self.calculate_slugging_percentage(hits, doubles, triples, home_runs, at_bats) [0, "0", ""].include?(at_bats) ? 0 : (((hits - doubles - triples - home_runs) + (2 * doubles) + (3 * triples) + (4 * home_runs)).to_f / at_bats).round(3) end |
.import_csv(file) ⇒ Object
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 |
# File 'lib/bstats/player_batting_stat.rb', line 11 def self.import_csv(file) begin CSV.foreach(file, headers: true) do |row| stat = PlayerBattingStat.new() stat.external_id = row['playerID'].to_s stat.year = row['yearID'].to_s stat.league = row['league'].to_s stat.team_id = row['teamID'].to_s stat.games = row['G'].to_i stat.at_bats = row['AB'].to_i stat.runs = row['R'].to_i stat.hits = row['H'].to_i stat.doubles = row['2B'].to_i stat.triples = row['3B'].to_i stat.home_runs = row['HR'].to_i stat.runs_batted_in = row['RBI'].to_i stat.stolen_bases = row['SB'].to_i stat.caught_stealing = row['CS'].to_i stat.batting_average = self.calculate_batting_average(stat.hits, stat.at_bats) stat.slugging_percentage = self.calculate_slugging_percentage(stat.hits, stat.doubles, stat.triples, stat.home_runs, stat.at_bats) stat.save end rescue CSV::MalformedCSVError => e # certain csv's have file endings that the CSV library doesn't like. Windows may or may not have something to do with that # TODO: log file ending failure end end |