這是我的解決方案:
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
要使用它,只是包括BeforeEach
到類像這樣:
class Superclass
include BeforeEach
def before_each
puts "Before Method" #this is supposed to be invoked by each extending class' method
end
end
class Subclass < Superclass
def my_method
#when this method is called, before_each_method method is supposed to get invoked
end
end
Subclass.new.my_method
# => Before Method
希望這會爲你工作!
[爲Ruby模塊中的每個方法調用執行代碼]的可能重複(http://stackoverflow.com/questions/5513558/executing-code-for-every-method-call-in-a-紅寶石模塊) –
恕我直言,這是一個不同的情況和一個非常好的問題。 – lucapette
http://stackoverflow.com/questions/29785454/call-before-methods-in-model-on-ruby/29837450#29837450弗雷德裏克解決方案 –