从Rails中的活动作业类中调用服务类

问题描述 投票:0回答:1

我有我的rails控制器类,它调用我的现役类

class Api::V2::Events::WegSessionsController < Api::V2::Events::ApplicationController
before_action :load_service

.... some code

def synchronize
@service.keep_cancelled = params[:keep_cancelled].to_b
if @service.valid_connection?

  WegJob.perform_later

  render json: {
    status: :ok,
    message: @service.message
  }, status: :ok
else
  render json: {
    status: :unprocessable_entity,
    errors: @event.errors.full_messages
  }, status: :ok
end
end

... some code

def load_service
  @service = WegService.new(event: @event)
end
end

我已经在Rails项目中将我的工作类别配置为使用Sidekiq并在此处调用服务方法

class WegJob < ApplicationJob
queue_as :default

def perform(*args)
 WegService.synchronize
end
end

此服务类具有'synchronize'方法的实现,我将从我的工作类中调用此方法

class WegService
 include ActiveModel::Model

... some code

def synchronize
 if event.weg_synced_at.present?
  update
 else
  create
 end

 event.update(weg_synced_at: Time.current)
end

... some code along with update and create method implementations.
end

执行此操作时,出现以下错误

[ActiveJob] [WegJob] [fd7c1869-6909-471c-bf32-9b2270a8c39c] Error performing 
WegJob (Job ID: fd7c1869-6909-471c-bf32-9b2270a8c39c) from Async(default) in 
2556.3ms: NoMethodError (undefined method `synchronize' for WegService:Class):

我知道从Job类调用服务方法的方式是错误的。我在哪里可能出错了?

ruby-on-rails background-process jobs sidekiq
1个回答
0
投票

您正在WegService中定义实例方法:

class WegService
 include ActiveModel::Model

... some code

def synchronize
 if event.weg_synced_at.present?
  update
 else
  create
 end

 event.update(weg_synced_at: Time.current)
end

... some code along with update and create method implementations.
end

但是您正在将其当作类方法来调用:

class WegJob < ApplicationJob
  queue_as :default

  def perform(*args)
    WegService.synchronize
  end
end

当然不起作用。将方法重新定义为类方法或创建工厂方法:

class WegService
  include ActiveModel::Model

  #.. some code

  def synchronize
    if event.weg_synced_at.present?
      update
    else
      create
    end

    event.update(weg_synced_at: Time.current)
  end

  def self.syncronize
    WegService.new.synchronize
  end
  # ... some code along with update and create method implementations.
end

但是对于服务对象,这是一个极其可疑的设计。这个名称含糊不清,服务对象实际上仅应具有调用方法。 include ActiveModel::Model还告诉我,您创建的内容实际上只是一个模型。

© www.soinside.com 2019 - 2024. All rights reserved.