Module: ConditionatorHooks

Defined in:
lib/conditionator/hooks.rb

Defined Under Namespace

Modules: ClassLevelConditionator Classes: PreconditionsNotMet

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



20
21
22
# File 'lib/conditionator/hooks.rb', line 20

def self.included(base)
  base.send :extend, ClassLevelConditionator
end

Instance Method Details

#failsafe_for(method) ⇒ Object



34
35
36
# File 'lib/conditionator/hooks.rb', line 34

def failsafe_for method
  self.class.data[self.class.name][method][:pre][:failsafe]
end

#load_conditionsObject

Creates all methods needed for the hooks to take place.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/conditionator/hooks.rb', line 39

def load_conditions

  _data = self.class.data
  _data[self.class.name] = {} if _data[self.class.name].nil?

  _data[self.class.name].each { |method, type|
    type.each { |_when, data|

      arr_methods = data[:methods]

      if !self.respond_to? "#{method}_with_#{_when}_cond".to_sym
        self.class.send :define_method, "#{method}_with_#{_when}_cond".to_sym do |*p|
          execute_method = true
          if(_when == :pre)
            returns = arr_methods.collect do |m| 
              self.send(m, *p) ? true : false
            end
            returns.uniq!

            #if one of the preconditions returned false, we act accordingly
            if returns.include? false
              execute_method = false
              if !data[:failsafe].nil? #if we had setup a failsafe method, we use that
                ret_value = self.send(data[:failsafe], *p) #if we execute the failsafe, that method will give us the returning value
              else #otherwise, we raise the exception if the dev didn't mute it
                raise PreconditionsNotMet if !data[:mute]
              end
            end
          end 
          if execute_method
            ret_value = self.send "#{method}_without_#{_when}_cond".to_sym, *p
          end
          if(_when == :post)
            arr_methods.each do |m| 
              self.send m, *p, ret_value 
            end
          end 
          return ret_value
        end
        self.class.send :alias_method, "#{method}_without_#{_when}_cond".to_sym, method
        self.class.send :alias_method, method, "#{method}_with_#{_when}_cond".to_sym
      end
    }
  }
end

#postconditionsObject



30
31
32
# File 'lib/conditionator/hooks.rb', line 30

def postconditions
  conditions :post
end

#preconditionsObject

Returns a list of all preconditions, grouped by the method they’re a precondition to.



26
27
28
# File 'lib/conditionator/hooks.rb', line 26

def preconditions
  conditions :pre
end