Module: SequelSimpleCallbacks::ClassMethods
- Defined in:
- lib/sequel_simple_callbacks.rb
Instance Method Summary collapse
-
#add_callback(chain, *args, &block) ⇒ Object
Add a callback hook to the model with parameters: * :if => One of [ Symbol, Proc ] (optional) * :unless => One of [ Symbol, Proc ] (optional) * :on => One of [ :create, :update ] (optional).
- #run_callbacks(model, hook) ⇒ Object
Instance Method Details
#add_callback(chain, *args, &block) ⇒ Object
Add a callback hook to the model with parameters:
-
:if => One of [ Symbol, Proc ] (optional)
-
:unless => One of [ Symbol, Proc ] (optional)
-
:on => One of [ :create, :update ] (optional)
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
# File 'lib/sequel_simple_callbacks.rb', line 60 def add_callback(chain, *args, &block) @callbacks ||= { } callbacks = @callbacks[chain] ||= [ ] # Extract the options from the arguments by testing if the last # is a Hash, otherwise default to an empty set. = (args[-1].is_a?(Hash)) ? args.pop : { } option_on = [:on] option_if = [:if] option_unless = [:unless] callbacks << lambda do |model| result = nil trigger = case (option_on) when :create model.new? when :update !model.new? when nil true else false end if (trigger and !option_if.nil?) trigger = case (option_if) when Symbol, String model.send(option_if) when Proc if (option_if.arity == 0) model.instance_eval(option_if) else option_if.call(model) end else option_if end end if (trigger and !option_unless.nil?) trigger = case (option_unless) when Symbol, String !model.send(option_unless) when Proc if (option_unless.arity == 0) !model.instance_eval(option_unless) else !option_unless.call(model) end else !option_unless end end if (trigger) args.each do |callback| result = case (callback) when Symbol, String model.send(callback) else if (callback.arity == 0) model.instance_eval(callback) else callback.call(model) end end break if (false === result) end end if (trigger and block) if (block.arity == 0) model.instance_eval(&block) else block.call(model) end end result end end |
#run_callbacks(model, hook) ⇒ Object
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
# File 'lib/sequel_simple_callbacks.rb', line 148 def run_callbacks(model, hook) return unless (@callbacks) callbacks = @callbacks[hook] return unless (callbacks) result = nil callbacks.each do |callback| result = callback.call(model) break if (result === false) end result end |