ruby-on-rails - 在哪里实例化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 中的完整示例:
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
推荐阅读
- java - 如何使用 ClassPathResource 从现有文件创建文件
- javascript - 如何在 jQuery CRM 动态门户中序列化查找字段
- reactjs - React VX 树状图抛出意外令牌 (125:14)
- laravel - 删除组件类只是为了使其匿名后出错
- laravel - Vue生产图像文件夹没有更新?
- c++ - 使用 C++ Boost 库在 INI 文件中使用重复的部分名称
- python - 正切方程提供错误的输出
- reactjs - 卡在后期预览组件中
- svg-animate - SVG AnimateTransform 在 Safari 中不起作用..?
- database - 具有 React.js 上下文概念的数据库