Class: Performify::Base

Inherits:
Object
  • Object
show all
Extended by:
Callbacks, Validation
Defined in:
lib/performify/base.rb

Constant Summary

Constants included from Callbacks

Callbacks::TYPES_OF_CALLBACK

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Callbacks

clean_callbacks, register_callback

Methods included from Validation

extended

Constructor Details

#initialize(current_user = nil, **args) ⇒ Base

Returns a new instance of Base.



12
13
14
15
16
17
18
19
# File 'lib/performify/base.rb', line 12

def initialize(current_user = nil, **args)
  @current_user = current_user
  @args = args

  prepare_instance

  fail!(with_callbacks: true) if errors?
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



10
11
12
# File 'lib/performify/base.rb', line 10

def args
  @args
end

#current_userObject (readonly)

Returns the value of attribute current_user.



9
10
11
# File 'lib/performify/base.rb', line 9

def current_user
  @current_user
end

Instance Method Details

#execute!Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/performify/base.rb', line 21

def execute!
  block_result = nil

  ActiveRecord::Base.transaction do
    begin
      block_result = yield
      if block_result
        success!(with_callbacks: false)
      else
        fail!(with_callbacks: false)
      end
    rescue RuntimeError, ActiveRecord::RecordInvalid
      fail!
    end

    raise ActiveRecord::Rollback if fail?
  end

  execute_callbacks
  block_result
end

#execute_callbacksObject



43
44
45
46
47
48
49
# File 'lib/performify/base.rb', line 43

def execute_callbacks
  if success?
    self.class.execute_callbacks(:success, self)
  elsif fail?
    self.class.execute_callbacks(:fail, self)
  end
end

#fail!(with_callbacks: true, errors: nil) ⇒ Object



57
58
59
60
61
62
# File 'lib/performify/base.rb', line 57

def fail!(with_callbacks: true, errors: nil)
  @result = false
  errors!(errors) unless errors.nil?
  execute_callbacks if with_callbacks
  @result
end

#fail?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/performify/base.rb', line 68

def fail?
  @result.blank?
end

#success!(with_callbacks: true) ⇒ Object



51
52
53
54
55
# File 'lib/performify/base.rb', line 51

def success!(with_callbacks: true)
  @result = true
  execute_callbacks if with_callbacks
  @result
end

#success?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/performify/base.rb', line 64

def success?
  @result.present?
end