首页 > 解决方案 > 在哪里实例化rails中的类

问题描述

我需要aws-sdk-comprehend在我的模型中使用 gem Metric,但我不确定是否可以(根据 rails 约定)在类之外实例化,例如:

comprehend = Aws::Comprehend::Client.new

class Metric < ApplicationRecord
  def key_phrases
    # Use comprehend object here.
  end
end

对于这种情况,是否有经验法则?我不想在 key_phrases 中实例化,因为每次我调用它时它都会实例化。

标签: ruby-on-railsruby

解决方案


答案已经在评论中发布。下面是它在惯用 Ruby 中的完整示例:

class Metric < ApplicationRecord
  def key_phrases
    # Use comprehend object here.
    comprehend_client
  end

  private

  def comprehend_client
    @comprehend_client ||= Aws::Comprehend::Client.new
  end
end

推荐阅读