Class: LightServiceObject::Base

Inherits:
Object
  • Object
show all
Extended by:
Dry::Initializer
Includes:
Dry::Monads::Result::Mixin
Defined in:
lib/light_service_object.rb

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.result_classObject (readonly)

Returns the value of attribute result_class.



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

def result_class
  @result_class
end

Class Method Details

.call(**options) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/light_service_object.rb', line 34

def self.call(**options)
  obj = self.new(**options)

  # Identify incoming params that weren't specified
  # set_params = obj.instance_variables.map{|e| e.to_s.tr("@","").to_sym }
  # unknown_params = (options.keys - set_params)
  # ap("#{self.name} > Unknown Parameters #{unknown_params}") if unknown_params.present?

  result = obj.call
  if self.result_class.present?
    if !result.is_a?(self.result_class)
      a_name = "#{self.result_class}"
      a_name = %w[a e i o u y].include?(a_name.first.downcase) ? "an #{a_name}" : "a #{a_name}"

      fail!("#{self.name} is not returning #{a_name}")
    end
  end

  Dry::Monads.Success(result)
rescue StandardError => error
  self.failed(error)
  Dry::Monads.Failure("#{self}: #{error}")
end

.expected_result_class(klass) ⇒ Object



25
26
27
28
# File 'lib/light_service_object.rb', line 25

def self.expected_result_class(klass)
  @result_class = klass
  @result_class = klass.constantize if klass.is_a?(String)
end

.failed(error) ⇒ Object



62
63
64
# File 'lib/light_service_object.rb', line 62

def self.failed(error)
  # Give subclasses a chance to see errors first
end

.optional(key, **options) ⇒ Object



20
21
22
23
# File 'lib/light_service_object.rb', line 20

def self.optional(key, **options)
  options[:optional] = true
  option(key, **options)
end

.param(key, **options) ⇒ Object

Raises:



12
13
14
# File 'lib/light_service_object.rb', line 12

def self.param(key, **options)
  raise Error.new("Do not use param in a service object")
end

.required(key, **options) ⇒ Object



16
17
18
# File 'lib/light_service_object.rb', line 16

def self.required(key, **options)
  option key, **options
end

Instance Method Details

#fail!(error) ⇒ Object



58
59
60
# File 'lib/light_service_object.rb', line 58

def fail!(error)
  raise (error.is_a?(String) ? Error.new(error) : error)
end