Sylar Sylar - 5 months ago 23
Ruby Question

Sum of all amount if charge dates are the same in Stripe

I'm iterating over a stripe charge object and I want to sum up the

total for each day.

# Returns an array object of charges for a customer
@customer_charges = Stripe::Charge.all(:customer => current_user.stripeid)


<% do |c| %>
On Monday, you were charged a total of <%= c.amount %>
<% end %>

Surely the above does nothing more than output lines of each charges but not the sum for the day. The difficulty I face is to sum up all charges for each day. Could someone point me in the right direction?

The output would be like:

"On Monday, you were charged a total of 200000"
"On Tueesday, you were charged a total of 500000"

Instead of:

On Monday, you were charged a total of 100000"
On Monday, you were charged a total of 100000"

looks messy with lines of
if statements
to compare dates and that does not look right.


You'll need to iterate through each charge object in Stripe, storing the amount and the parsed date for each charge:

# Fetch charges in batches of 100 records from Stripe API, yield each individual charge to a block.
def each_stripe_charge_for_customer(customer_id)
  starting_after = nil
  loop do
    charges = Stripe::Charge.all(customer: customer_id, limit: 100, starting_after: starting_after)
    break if == 0
    charges.each do |charge|
      yield charge
    starting_after =

charges_by_date =

# For each Stripe charge, store the date and amount into a hash.
each_stripe_charge_for_customer(current_user.stripeid) do |stripe_charge|
  # Parses Stripe's timestamp to a Ruby date object. `to_date` converts a DateTime object to a date (daily resolution).
  charge_date =
  charge_amount = stripe_charge.amount

  charges_by_date[charge_date] += charge_amount