ruby-on-rails - Ruby on Rails 服务的最佳实践
问题描述
我正在编写一些移动 otp 验证服务,下面是我的服务类
require 'nexmo'
class NexmoServices
def initialize api_key = nil, api_secret = nil, opts = {}
api_key = api_key || Rails.application.secrets.nexmo_api_key
api_secret = api_secret || Rails.application.secrets.nexmo_secret_key
@nexmo_client = Nexmo::Client.new(
api_key: api_key,
api_secret: api_secret,
code_length: 6
)
@brand = 'CryptoShop'
end
def send_verification_code opts
@nexmo_client.verify.request(number: opts[:number], brand: @brand)
end
def check_verification_code opts
@nexmo_client.verify.check(request_id: opts[:request_id], code: opts[:verification_code])
end
def cancel_verification_code opts
@nexmo_client.verify.cancel(opts[:request_id])
end
end
在控制器中,我正在调用如下服务方法
class NexmoController < ApplicationController
def send_verification_code
response = NexmoServices.new.send_verification_code params[:nexmo]
if response.status == '0'
render json: response.request_id.to_json
else
render json: response.error_text.to_json
end
end
def cancel_verification_code
response = NexmoServices.new.cancel_verification_code params[:nexmo]
if response.status == '0'
render json: response.to_json
else
render json: response.error_text.to_json
end
end
end
我读过通常在服务类中会有调用方法,控制器会调用它。服务方法调用将负责其余的工作。
如果您看到我的控制器(NexmoService.new),我的情况就是为所有方法实例化服务对象。
这是对的吗???我想知道在这种情况下必须遵循最佳实践。
谢谢, 阿吉斯
解决方案
推荐阅读
- c# - EF Core 2.2 GroupBy FirstOrDefault 的替代方案
- ios - 如何使用cornerRadius为SwiftUI中的按钮提供阴影
- tsql - I got one problem in SQL,i need to get start of next minute value
- python - Igraph runs in Python console but not from script
- sqlite - 如果 BOOL 列设置为“true”,从一列中提取数据的 SQLite 查询是什么?
- react-native - Jest snapshot testing of FlatList renderItem
- linux - 是否可以在当前 shell 中禁用 sudo 超时?
- python - How can I split a numerical column depending on the value of another column?
- c# - Can we get IP address in an MVC Ajax call
- python - How do I make a Python Program demonstrating Zipf's Law?