Class: SimpleAction::Service

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming, AcceptsParams, Transactable
Includes:
ActiveModel::Conversion, DelegatesToParams
Defined in:
lib/simple_action/service.rb

Instance Attribute Summary

Attributes included from AcceptsParams

#params_class

Class Method Summary collapse

Instance Method Summary collapse

Methods included from AcceptsParams

api_pie_documentation

Methods included from Transactable

transaction, transaction?, transaction_options

Methods included from DelegatesToParams

#method_missing, #respond_to?

Constructor Details

#initialize(params = {}) ⇒ Service

Returns a new instance of Service.



38
39
40
41
42
43
44
# File 'lib/simple_action/service.rb', line 38

def initialize(params={})
  @raw_params = params
  @params = self.class.params_class.new(params)
  @initial_params_valid = nil
  @result = nil
  @has_run = false
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class SimpleAction::DelegatesToParams

Class Method Details

.run(params = {}) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/simple_action/service.rb', line 15

def run(params = {})
  instance = self.new(params)
  instance.mark_as_ran
  result = transaction do
    if instance.valid?
      outcome = instance.execute
      instance.errors.empty? ? outcome : nil
    end
  end
  instance.set_result(result)
  instance
end

.run!(params = {}) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/simple_action/service.rb', line 28

def run!(params = {})
  response = run(params)
  if response.valid?
    response.result
  else
    raise ExecutionError, response.errors.to_s
  end
end

Instance Method Details

#errorsObject



54
55
56
# File 'lib/simple_action/service.rb', line 54

def errors
  @params.errors
end

#executeObject



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

def execute
  raise ImplementationError, "subclasses must implement 'execute' method."
end

#mark_as_ranObject



79
80
81
# File 'lib/simple_action/service.rb', line 79

def mark_as_ran
  @has_run = true
end

#paramsObject



46
47
48
# File 'lib/simple_action/service.rb', line 46

def params
  @params
end

#persisted?Boolean

Returns:

  • (Boolean)


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

def persisted?
  false
end

#resultObject Also known as: value



70
71
72
# File 'lib/simple_action/service.rb', line 70

def result
  @result
end

#set_result(result = nil) ⇒ Object



75
76
77
# File 'lib/simple_action/service.rb', line 75

def set_result(result = nil)
  @result = result
end

#success?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/simple_action/service.rb', line 66

def success?
  valid? && @has_run
end

#valid?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/simple_action/service.rb', line 50

def valid?
  initial_params_valid? && errors.empty?
end