我有一个Sidekiq工作程序,并在其中使用了case语句:
module Api
def self.authenticate(company_id)
Thread.current['api_company_id'] = company_id
yield if block_given?
ensure
Thread.current['api_company_id'] = nil
end
end
module Apis
class PollTrackableJobWorker
include Sidekiq::Worker
class EDocumentNotDoneError < StandardError; end
class UnhandledCaseError < StandardError; end
def perform(job_id, _invoice_id)
Api.authenticate(1) do
response = Api::TrackableJob.find(job_id).first
case response['status']
when 'done' then return true
when 'error' then return handle_error(response['errors'])
when 'pending' || 'running' then return raise EDocumentNotDoneError
else raise UnhandledCaseError, response
end
end
end
private
def handle_error(exception)
Bugsnag.notify(exception) if defined?(Bugsnag)
end
end
end
#perform
方法针对所有可能的结果进行了测试。以下是done
的情况:
class PollTrackableJobWorkerTest < ActiveSupport::TestCase
test 'status is done' do
response = {
'type' => 'trackable_jobs',
'id' => 'xxxxx',
'status' => 'done',
'errors' => nil
}
Api.expects(:authenticate).with(1).yields
Api::TrackableJob.stubs(:find).with('xxxxx').returns([response])
assert_equal(true, Apis::PollTrackableJobWorker.new.perform('xxxxx', 123))
end
end
测试顺利通过。
但是,当我使用隐式return
时,它一直失败(返回nil
)。
例如,将私有方法与显式return
语句一起使用会失败
case response['status']
when 'done' then returns_true
# code omitted
end
private
def returns_true
return true
end
或使用隐式return
也会失败
when 'done' then true
为什么对案例陈述需要明确的return
?