2012-10-08 20 views
0

現在我正在構建一個通話跟蹤應用程序來學習rails和twilio。該應用程序有2個相關模型;計劃模式has_many用戶。計劃表的值也是max_minutes。需要不斷運行的if/than語句在哪裏出現在rails中?

我希望它能夠讓特定用戶在超過max_minutes時,其子帳戶被禁用,並且我還可以警告他們在視圖中升級。

要做到這一點,這是我在User類

def at_max_minutes? 
    time_to_bill=0 
    start_time = Time.now - (30 * 24 * 60 * 60) #30 days 
    @subaccount = Twilio::REST::Client.new(@user.twilio_account_sid, @user.twilio_auth_token) 
    @subaccount.calls.list({:page => 0, :page_size => 1000, :start_time => ">#{start_time.strftime("%Y-%m-%d")}"}).each do |call| 
     time_to_bill += (call.duration.to_f/60).ceil 
    end 

    time_to_bill >= self.plan.max_minutes 

    end 

這讓我跑,如果在視圖/ else語句,敦促他們升級創造了一個參數。然而,我還想做一個if/else語句,如果at_max_minutes?比用戶的twilio子帳戶被禁用,否則啓用。

我不知道我會把它放在軌道上。

這將是這個樣子

@client = Twilio::REST::Client.new(@user.twilio_account_sid, @user.twilio_auth_token) 
    @account = @client.account 
    if at_max_minutes? 
    @account = @account.create({:status => 'suspended'}) 
    else 
    @account = @account.create({:status => 'active'}) 
    end 

,但我不知道,我會把這個代碼,因此它的積極的所有時間。

您將如何實現此代碼,以使其功能正常工作?

回答

0

不是不斷計算at_max_minutes?中使用的總分鐘數,爲什麼不跟蹤用戶使用的分鐘數,並將狀態設置爲過渡時間(當使用分鐘數超過max_minutes時)。然後,您的視圖和調用代碼只需檢查狀態(您可能還想直接在用戶上存儲狀態,以將API調用保存到Twilio中)。

添加到用戶模式:

used_minutes 

當每一個通話結束後,更新分鐘:

def on_call_end(call) 
    self.used_minutes += call.duration_in_minutes # this assumes Twilio gives you a callback and has the length of the call) 
    save! 
end 

添加到after_save的用戶:

after_save :check_minutes_usage 

def check_minutes_usage 
    if used_minutes >= plan.max_minutes 
    @account = @account.create({:status => 'suspended'}) 
    else 
    @account = @account.create({:status => 'active'}) 
    end 
end 
+0

感謝這個尼克!這聽起來像一個好主意 - 我必須先記錄一些測試數據,然後我會告訴你它是如何發生的。 –

0

如果您希望它始終處於「活動狀態」,那麼您將不得不爲此檢查執行某種計劃後臺工作。我建議resqueresque-scheduler,這是一個很好的Rails調度解決方案。基本上,你要做的是做一份工作,它執行你指定的第二塊代碼,並使它定期運行(可能每隔2小時)。