Skip to content

Instantly share code, notes, and snippets.

@apeiros
Forked from babney/method_cop.rb
Created October 31, 2011 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apeiros/1329347 to your computer and use it in GitHub Desktop.
Save apeiros/1329347 to your computer and use it in GitHub Desktop.
MethodCop
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