首页 > 解决方案 > 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),我的情况就是为所有方法实例化服务对象。

这是对的吗???我想知道在这种情况下必须遵循最佳实践。

谢谢, 阿吉斯

标签: ruby-on-railsrubyruby-on-rails-4

解决方案


推荐阅读