Class: Warped::Services::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/warped/services/base.rb

Overview

Base class for all services

This class provides a simple interface for creating services. It also provides a way to call services asynchronously using ActiveJob.

Examples:

Create a service

class PrintService < Warped::Services::Base
  def call(message)
    puts message
  end
end

SomeService.call('Hello World') # => "Hello World"
SomeService.new('Hello World').call # => "Hello World"

Call a service asynchronously

class SlowService < Warped::Services::Base
  enable_job!

  def call(message)
    sleep 5
    puts message
  end
end

SlowService.call_later('Hello World') # => "Hello World" after 5 seconds
SlowService::Job.perform_later('Hello World') # => "Hello World" after 5 seconds

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.callObject



35
36
37
# File 'lib/warped/services/base.rb', line 35

def self.call(...)
  new(...).call
end

.call_laterObject



39
40
41
42
43
44
45
46
# File 'lib/warped/services/base.rb', line 39

def self.call_later(...)
  unless @job_enabled
    message = "#{self.class.name}::Job is not implemented, make sure to call enable_job! in the service"
    raise NotImplementedError, message
  end

  self::Async.perform_later(...)
end

.enable_job!Object

This method is used to create a Job class that inherits from Warped::Jobs::Base and calls the service asynchronously.

Examples:

Enable async for a service

class SomeService < Warped::Services::Base
  enable_job!

  def call(...)
    # service logic
  end
end

# SomeService.call_later(...)
# SomeService::Job.perform_later(...)


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/warped/services/base.rb', line 65

def self.enable_job!
  @job_enabled = true

  class_eval <<-RUBY, __FILE__, __LINE__ + 1
    # class SomeService
    #   class Job < Warped::Jobs::Base
    #
    #     def perform(...)
    #       SomeService.call(...)
    #     end
    #   end
    #
    #   def self.call_later(...)
    #     Job.perform_later(...)
    #   end
    # end
    class Job < Warped::Jobs::Base
      def perform(...)
        #{name}.call(...)
      end
    end

    def self.call_later(...)
      Job.perform_later(...)
    end
  RUBY
end

Instance Method Details

#callObject

Raises:

  • (NotImplementedError)


48
49
50
# File 'lib/warped/services/base.rb', line 48

def call
  raise NotImplementedError, "#{self.class.name}#call not implemented"
end