-
-
Save apeiros/1329347 to your computer and use it in GitHub Desktop.
MethodCop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module MethodCop | |
# guard methods that have side effects with a callback that fires before the method is invoked. If the callback returns a "falsey" value, | |
# the method is halted and will not be called. The callback will return nil instead. | |
# if the method does not have side effects or you depend on its return value, you should NOT use this on that method! | |
def guard_method(guarded_method, guard=nil, &callback) | |
# normalize guard | |
guard = method(guard) if guard.is_a?(Symbol) | |
guard = callback if callback | |
raise ArgumentError, "You can only supply either a guard argument or a block" if block && guard | |
raise ArgumentError, "guard argument must respond to call" unless guard.respond_to?(:guard) | |
original = method(guarded_method) | |
define_method(guarded_method) do |*args, &block| | |
original.call(*args, &block) if guard.call(*args, &block) | |
end | |
end | |
end | |
class Testing | |
extend MethodCop | |
def some_method | |
return "I'm about to do something horribly wrong." | |
end | |
def run_method? | |
# block everything | |
return false | |
end | |
guard_method :some_method, :run_method? | |
guard_method :some_method do false end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment