2016-04-30 62 views
1

我正在遍歷stripe charge object,我想總計每天的總計amount如果條形碼中的收費日期相同,所有金額的總和

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

瀏覽:

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

當然上面做無非是每個收費輸出線以上,但不是當天的總和。我面臨的困難是總結每一天的所有費用。有人能指出我正確的方向嗎?

輸出會是這樣:

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

相反的:

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

view看起來雜亂無章與if statements線比較日期,並且看起來不正確的。

+0

你或許應該使用'這裏,而不是'map' each'。什麼是「創造」?那是一列還是一種方法 – tadman

+0

好的。 'created'是條紋的json unix timestamp:''created「:1462001409,' – Sylar

+0

你爲什麼總計時間戳?這對我來說毫無意義。如果你需要它們作爲日期,'Time.at(timestamp)'將會轉換。 – tadman

回答

2

你需要通過條紋每次充電對象上進行迭代,存儲量和每個負責解析日期:

# 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 
    customer_charges = Stripe::Charge.all(customer: customer_id, limit: 100, starting_after: starting_after) 
    break if customer_charges.none? 
    charges.each do |charge| 
     yield charge 
    end 
    starting_after = charges.data.last.id 
    end 
end 

charges_by_date = Hash.new(0) 

# 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 = Time.at(stripe_charge.created).to_date 
    charge_amount = stripe_charge.amount 

    charges_by_date[charge_date] += charge_amount 
end 
+0

這是相當不錯的,但有幾件事:如果您希望默認值爲0,則'charges_by_date'可以是'Hash.new(0)',這樣可以避免稍後使用'|| ='測試。 「Date.strptime」比簡單地完成工作的Time.at文件要笨得多。 – tadman

+0

我會稍後再去。謝謝 – Sylar

+0

@tadman不知道'Hash.new(0)',謝謝。 –