From 5fa09b89db99b70ad5e5841b89454df6d7c3d4ce Mon Sep 17 00:00:00 2001 From: ytti Date: Thu, 14 Jun 2018 00:01:00 +0300 Subject: Model callback enhancement Allows cfg, cmd, pre, post and expect blocks to reset the callback array or change from push to unshift. Use case is in custom models which monkey-patch the distribution model. You might want to replace for example distribution ```cmd :secret``` with your own version, like such: cmd :secret clear: true do ... end Or if you instead want to unshift your block to be first to be called: cfg :ssh do prepend: true do .. end Closes #1384 --- lib/oxidized/model/model.rb | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) (limited to 'lib/oxidized/model') diff --git a/lib/oxidized/model/model.rb b/lib/oxidized/model/model.rb index 438357f..761e19e 100644 --- a/lib/oxidized/model/model.rb +++ b/lib/oxidized/model/model.rb @@ -24,9 +24,9 @@ module Oxidized @prompt or @prompt = _prompt end - def cfg *methods, &block + def cfg *methods, **args, &block [methods].flatten.each do |method| - @cfg[method.to_s] << block + process_args_block(@cfg[method.to_s], args, block) end end @@ -34,11 +34,11 @@ module Oxidized @cfg end - def cmd _cmd = nil, &block + def cmd _cmd = nil, **args, &block if _cmd.class == Symbol - @cmd[_cmd] << block + process_args_block(@cmd[_cmd], args, block) else - @cmd[:cmd] << [_cmd, block] + process_args_block(@cmd[:cmd], args, [_cmd, block]) end Oxidized.logger.debug "lib/oxidized/model/model.rb Added #{_cmd} to the commands list" end @@ -47,8 +47,8 @@ module Oxidized @cmd end - def expect re, &block - @expect << [re, block] + def expect re, **args, &block + process_args_block(@expect, args, [re, block]) end def expects @@ -62,8 +62,8 @@ module Oxidized # @since 0.0.39 # @yield expects block which should return [String] # @return [void] - def pre &block - @procs[:pre] << block + def pre **args, &block + process_args_block(@procs[:pre], args, block) end # calls the block at the end of the model, adding the output of the block @@ -73,8 +73,8 @@ module Oxidized # @since 0.0.39 # @yield expects block which should return [String] # @return [void] - def post &block - @procs[:post] << block + def post **args, &block + process_args_block(@procs[:post], args, block) end # @author Saku Ytti @@ -83,6 +83,17 @@ module Oxidized def procs @procs end + + private + + def process_args_block(target, args, block) + if args[:clear] + target.replace([block]) + else + method = args[:prepend] ? :unshift : :push + target.send(method, block) + end + end end attr_accessor :input, :node -- cgit v1.2.1