Class: RailsBase::ServiceBase

Inherits:
Object
  • Object
show all
Includes:
Interactor, ServiceLogging
Defined in:
app/services/rails_base/service_base.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ServiceLogging

#aletered_message, #class_name, #log, #log_prefix, #logger, #service_id

Class Method Details

.inherited(subclass) ⇒ Object



7
8
9
10
11
12
# File 'app/services/rails_base/service_base.rb', line 7

def self.inherited(subclass)
  # Add the base logging to the subclass.
  # Since this is done at inheritence time it should always be the first and last hook to run.
   subclass.around(:service_base_logging)
  subclass.around(:internal_validate)
end

Instance Method Details

#internal_validate(interactor) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/services/rails_base/service_base.rb', line 18

def internal_validate(interactor)
  # call validate that is overidden from child
  begin
    validate!
  rescue StandardError => e
    log(level: :error, msg: "Error during validation. #{e.message}")
    raise
  end

  # call interactor
  interactor.call
end

#service_base_logging(interactor) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'app/services/rails_base/service_base.rb', line 31

def service_base_logging(interactor)
 beginning_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  # Pre processing stats
  log(level: :info, msg: 'Start')

  # Run the job!
  interactor.call

  # Set status for use in ensure block
  status = :complete

# Capture Interactor::Failure for logging purposes, then reraise
rescue ::Interactor::Failure
  # set status for use in ensure block
  status = :failure

  # Reraise to let the core Interactor handle this
  raise
# Capture exception explicitly to try to logging purposes. Then reraise.
rescue ::Exception => e # rubocop:disable Lint/RescueException
  # set status for use in ensure block
  status = :error

  # Log error
  log(level: :error, msg: "Error #{e.class.name}")

  raise
ensure
  # Always log how long it took along with a status
  finished_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  elapsed = ((finished_time - beginning_time)).round(1)
  log(level: :info, msg: "Finished with [#{status}]...elapsed #{elapsed}s")
end

#validate!Object



14
15
16
# File 'app/services/rails_base/service_base.rb', line 14

def validate!
  # overload from child
end