Skip to content

Instantly share code, notes, and snippets.

@benolee
Last active December 16, 2015 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benolee/bc1ac4df35cc3fba0e08 to your computer and use it in GitHub Desktop.
Save benolee/bc1ac4df35cc3fba0e08 to your computer and use it in GitHub Desktop.

example usage

$ bundle install
$ irb
>> require "./gpa"
-- create_table(:courses)
   -> 0.0088s
-- create_table(:students)
   -> 0.0007s
=> true

>> susan = Student.create! name: "Susan"
=> #<Student id: 2, name: "Susan">

>> susan.courses.create! name: "Underwater Basket Weaving", grade_points: 4, credit_hours: 3
=> #<Course id: 3, student_id: 2, name: "Underwater Basket Weaving", grade_points: #<BigDecimal:102824b70,'0.4E1',9(36)>, credit_hours: #<BigDecimal:102824aa8,'0.3E1',9(36)>>

>> susan.courses.create! name: "Quantum Physics", grade_points: 0, credit_hours: 4
=> #<Course id: 4, student_id: 2, name: "Quantum Physics", grade_points: #<BigDecimal:10283c798,'0.0',9(36)>, credit_hours: <BigDecimal:10283c6d0,'0.4E1',9(36)>>

>> puts susan.calculate_gpa
0.571428571428571429
#=> nil
source 'https://rubygems.org'
gem 'activerecord'
gem 'sqlite3'
require 'bundler/setup'
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Schema.define do
create_table :courses do |t|
t.belongs_to :student
t.string :name
t.decimal :grade_points
t.decimal :credit_hours
end
create_table :students do |t|
t.string :name
end
end
class Course < ActiveRecord::Base
belongs_to :student
validates :grade_points, :credit_hours, presence: true, numericality: true
end
class Student < ActiveRecord::Base
has_many :courses
def calculate_gpa
courses.sum(:grade_points) / courses.sum(:credit_hours)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment