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
  • Select an option

  • Save apeiros/1329347 to your computer and use it in GitHub Desktop.

Select an option

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(name, options)
method = name.to_sym
original_method = "#{name}_orig".to_sym
alias_method original_method, method
define_method(name.to_sym) do
unless options[:with].nil?
unless !self.send(options[:with].to_sym)
self.send(original_method)
else
# THIS METHOD IS UNDER ARREST
nil
end
else
# no method to guard with was given
self.send(method)
end
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, :with => :run_method?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment