Skip to content

Instantly share code, notes, and snippets.

@kevin-cantwell
Created April 9, 2014 23:53
Show Gist options
  • Save kevin-cantwell/10331243 to your computer and use it in GitHub Desktop.
Save kevin-cantwell/10331243 to your computer and use it in GitHub Desktop.
class Budget < ActiveRecord::Base
attr_accessible :budget, :expenses, :start_date, :end_date, :purchases_attributes
has_many :purchases
accepts_nested_attributes_for :purchases, :allow_destroy => true
def perdiem
if remaining_days > 0
((projected_spend_so_far - actual_spend_so_far) / remaining_days) + initial_perdiem
else
available_funds - actual_spend_so_far
end
end
def initial_perdiem
available_funds / total_days.to_f
end
def available_funds
budget - expenses
end
def actual_spend_so_far
purchases.sum(&:amount) - spent_today
end
def projected_spend_so_far
initial_perdiem * (total_days - remaining_days)
end
def remaining_budget
available_funds - actual_spend_so_far - spent_today
end
def remaining_days
if now_utc.beginning_of_day < start_date.utc.beginning_of_day
total_days
else
(end_date.utc.beginning_of_day.to_i - now_utc.beginning_of_day.to_i) / 86400
end
end
def total_days
(end_date.utc.beginning_of_day.to_i - start_date.utc.beginning_of_day.to_i) / 86400
end
def title
"#{start_date.utc.strftime("%m/%d/%Y")} - #{end_date.utc.strftime("%m/%d/%Y")}"
end
def spent_today
purchases.select{|p| p.created_at >= (now_utc.beginning_of_day)}.sum(&:amount)
end
def now_utc
Time.now.utc
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment