Class: ApplicationService::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model
Defined in:
lib/application_service.rb

Overview

The Base class within the ApplicationService module provides a standard interface for calling service objects. It leverages ActiveModel for initialization with keyword arguments and input validation.

Example usage:

class Sum < ApplicationService::Base
  attr_accessor :number_a, :number_b

  validates :number_a, :number_b, presence: true, numericality: { greater_than: 0 }

  def call
    number_a + number_b
  end
end

sum = Sum.call(number_a: 1, number_b: 2) # => 3

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**kwargs) ⇒ Base

Initializes a new instance of the service object.

Parameters:

  • kwargs (Hash)

    The attributes to be passed to the service object.

Raises:

  • (NotImplementedError)

    if an attempt is made to instantiate the Base class directly.



34
35
36
37
38
39
40
# File 'lib/application_service.rb', line 34

def initialize(**kwargs)
  super

  return unless instance_of?(Base)

  raise ::NotImplementedError, "#{self.class.name} is an abstract class and cannot be instantiated directly"
end

Class Method Details

.call(**kwargs) ⇒ Object, false

Instantiates a new service object and invokes its ‘call` method.

Parameters:

  • kwargs (Hash)

    The attributes to be passed to the service object.

Returns:

  • (Object)

    The result of the service object’s call method.

  • (false)

    If the service object is invalid.



47
48
49
50
51
52
# File 'lib/application_service.rb', line 47

def self.call(**kwargs)
  service = new(**kwargs)
  return false unless service.valid?

  service.call
end

Instance Method Details

#callObject

Encapsulates the implementation to be executed by the service object.

Raises:

  • (NotImplementedError)

    if the method is not implemented in a child class.



57
58
59
# File 'lib/application_service.rb', line 57

def call
  raise ::NotImplementedError, "The `call` method must be implemented in #{self.class.name}"
end