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 Method Summary collapse

Instance Method Summary collapse

Class Method Details

.call(**options) ⇒ Object



73
74
75
76
77
78
79
80
# File 'lib/light_service_object.rb', line 73

def call(**options)
  begin
    obj = self.new(**options)
    obj.call
  rescue KeyError => error
    Dry::Monads.Failure(error.message)
  end
end

.expected_result_class(klass) ⇒ Object



68
69
70
71
# File 'lib/light_service_object.rb', line 68

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

.failed(error) ⇒ Object



83
84
# File 'lib/light_service_object.rb', line 83

def self.failed(error)
end

.option(*args, **opts, &block) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/light_service_object.rb', line 49

def option(*args, **opts, &block)
  if opts.delete(:mutable)
    name = opts[:as] || args.first
    self.send("attr_writer", name)
  end
  super(*args, **opts, &block)
end

.optional(key, **options) ⇒ Object



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

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

.param(key, **options) ⇒ Object

Raises:

  • (Error)


45
46
47
# File 'lib/light_service_object.rb', line 45

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

.required(key, **options) ⇒ Object



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

def required(key, **options)
  options[:private] = true
  option(key, **options)
end

.result_classObject



41
42
43
# File 'lib/light_service_object.rb', line 41

def result_class
  @result_class
end

Instance Method Details

#callObject



91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/light_service_object.rb', line 91

def call
  result = self.perform
  if self.result_class
    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 Exception => error
  Dry::Monads.Failure(error.message)
end

#error_reason(error) ⇒ Object



113
114
115
116
# File 'lib/light_service_object.rb', line 113

def error_reason(error)
  # Give subclasses a chance to see errors first
  "[#{self.class}] #{error}"
end

#fail!(error) ⇒ Object



106
107
108
109
110
111
# File 'lib/light_service_object.rb', line 106

def fail!(error)
  error = ServiceError.new(error.to_s) if !error.is_a?(ServiceError)
  reason = self.error_reason(error)
  self.class.failed(error)
  raise error
end

#result_classObject

— INSTANCE METHODS



87
88
89
# File 'lib/light_service_object.rb', line 87

def result_class
  self.class.result_class
end