Skip to content

Instantly share code, notes, and snippets.

@ream88
Created August 21, 2011 12:56
Show Gist options
  • Select an option

  • Save ream88/1160583 to your computer and use it in GitHub Desktop.

Select an option

Save ream88/1160583 to your computer and use it in GitHub Desktop.
Before each method hook
require 'active_support/all'
module BeforeEach
extend ActiveSupport::Concern
module InstanceMethods
def before_each
raise NotImplementedError('Please define before_each method')
end
end
module ClassMethods
def method_added(method)
method = method.to_s.gsub(/_with(out)?_before$/, '')
with_method, without_method = "#{method}_with_before", "#{method}_without_before"
return if method == 'before_each' or method_defined?(with_method)
define_method(with_method) do |*args, &block|
before_each
send(without_method, *args, &block)
end
alias_method_chain(method, :before)
end
end
end
class Foo
include BeforeEach
def before_each
puts 'bar'
end
def foo
puts 'foo'
end
end
puts Foo.new.foo
# => bar
# foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment