0

现在我正在构建一个呼叫跟踪应用程序来学习 rails 和 twilio。该应用程序有2个相关模型;计划模型有_许多用户。计划表也有值 max_minutes。

我希望它做到这一点,以便当特定用户超过他们的 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 

这允许我在视图中运行 if/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

但是,我不确定我会将这段代码放在哪里,以便它一直处于活动状态。

您将如何实现此代码以使功能正常工作?

4

2 回答 2

0

如果您希望它“一直处于活动状态”,您将不得不为此检查执行某种预定的后台作业。我推荐resqueresque-scheduler,这是一个非常好的 Rails 调度解决方案。基本上你要做的是做一个工作,它执行你指定的第二个代码块,并让它定期运行(可能每 2 小时)。

于 2012-10-08T16:56:03.173 回答
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
于 2012-10-08T20:55:44.307 回答