Class: Rails::Service Abstract

Inherits:
Object
  • Object
show all
Includes:
Callable
Defined in:
lib/rails/service.rb

Overview

This class is abstract.

Abstract base class for all 3rd party services

Provides:

- Configuration (automatically loaded from `config/services/[service_name].yml`, available as `config`)
- Logging (to separate log file `log/services/[service_name].log`, call via `logger.info(msg)`)
- Call style invocation (like `PDFGenerationService.(some, params)`)

Examples:

class Services::PDFGenerationService < Service
  def initialize
    super('pdf_generation')
  end

  def call(action, *args)
     ... here happens the magic! ...
  end
end

PDFGenerationService.(some, params)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(service_name = nil) ⇒ Service

Constructor. Call this from the subclass with the service name, like ‘super ’pdf_generator’‘. After that you can access the config and logger.

Parameters:

  • service_name (String) (defaults to: nil)

    Name of the service, like ‘pdf_generator’.

Raises:

  • (NotImplementedError)

    When this class is tried to be instantiated without subclass.

  • (RuntimeError)

    When no service_name is given



40
41
42
43
44
45
46
47
48
# File 'lib/rails/service.rb', line 40

def initialize(service_name = nil)
  raise NotImplementedError if self.class == Service
  raise 'Please provide a service name!' if service_name.nil?

  @service_name = service_name

  setup_logger
  setup_configuration
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



31
32
33
# File 'lib/rails/service.rb', line 31

def config
  @config
end

#loggerObject (readonly)

Returns the value of attribute logger.



31
32
33
# File 'lib/rails/service.rb', line 31

def logger
  @logger
end

#service_nameObject (readonly)

Returns the value of attribute service_name.



31
32
33
# File 'lib/rails/service.rb', line 31

def service_name
  @service_name
end

Class Method Details

.callObject

Allows call syntax on class level: SomeService.(some, args)



124
125
126
# File 'lib/rails/service.rb', line 124

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

Instance Method Details

#call(options) ⇒ Object

Abstract method for instance call. Implement this in the subclass!

Raises:

  • (NotImplementedError)

    When this is not overwritten in the subclass



120
# File 'lib/rails/service.rb', line 120

def call(options); end

#helpersObject

Allows to use rails view helpers



129
130
131
# File 'lib/rails/service.rb', line 129

def helpers
  ApplicationController.new.helpers
end