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.



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

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

  return if args.empty?

  validate(args).each do |arg_name, arg_value|
    define_singleton_method(arg_name) { arg_value }
  end

  fail!(with_callbacks: true) if errors?
end

Instance Attribute Details

#current_user ⇒ Object (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



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

def execute!
  return if defined?(@result)

  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_callbacks ⇒ Object



47
48
49
50
51
52
53
# File 'lib/performify/base.rb', line 47

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) ⇒ Object



61
62
63
64
65
# File 'lib/performify/base.rb', line 61

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

#fail? ⇒ Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/performify/base.rb', line 71

def fail?
  @result.blank?
end

#success!(with_callbacks: true) ⇒ Object



55
56
57
58
59
# File 'lib/performify/base.rb', line 55

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

#success? ⇒ Boolean

Returns:

  • (Boolean)


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

def success?
  @result.present?
end