Skip to content

Instantly share code, notes, and snippets.

@jkgraham
Last active August 29, 2015 14:06
Show Gist options
  • Save jkgraham/9f69b59e4d32a680212f to your computer and use it in GitHub Desktop.
Save jkgraham/9f69b59e4d32a680212f to your computer and use it in GitHub Desktop.
Refactor problem
# Introduced these two classes to the students and asked them to refactor/improve the `calculate_balance` method.
# We initially suggested maybe breaking up the method in to smaller ones.
class Invoice < ActiveRecord::Base
belongs_to :account
def calculate_balance
if display_ids.present?
items = account.items.visible.where("id IN (#{display_ids})").oldest_first
else
items = account.items.visible.where("created_at > ? AND created_at < ?", starts_at, ends_at).oldest_first
end
total = 0
if account.due_at < Time.zone.now
total += account.late_fee
end
items.each do |x|
total += x.amount
end
if account.due_at < Time.zone.now
self.late = true
end
self.total = total
save
end
end
class Account < ActiveRecord::Base
has_many :invoices
attr_accessible :due_at
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment