/ Published in: Ruby
Allows you to create before and after methods in a class
Examplerequire "before_and_after"
class Message
include BeforeAndAfter
def initialize message
@message = message
end
def display
puts @message
end
def before_display
puts "BEFORE DISPLAY"
end
def after_display
puts "AFTER DISPLAY"
end
use_method :display
end
Message.new( "== MESSAGE ==" ).display
Outputs
BEFORE DISPLAY
== MESSAGE ==
AFTER DISPLAY
before_and_after.rb
Expand |
Embed | Plain Text
module BeforeAndAfter # This extends the class that includes BeforeAndAfter with the methods in ClassMethods def self.included(base) base.extend(ClassMethods) end module ClassMethods def use_method *methods methods.each { |method| # Set up the before and after variables before_method = "before_#{method.to_s}".to_sym after_method = "after_#{method.to_s}".to_sym # Unbind the original, before, and after methods unbinded_before_method = instance_method( before_method ) unbinded_method = instance_method( method ) unbinded_after_method = instance_method( after_method ) # Define the before and after methods if they don't already exist define_method( before_method ) unless self.method_defined?( before_method ) define_method( after_method ) unless self.method_defined?( after_method ) # Redefines the method to run the before and after methods define_method( method ) { unbinded_before_method.bind( self ).call # Bind the unbinded BEFORE method unbinded_method.bind( self ).call # Bind the original method unbinded_after_method.bind( self ).call # Bind the unbinded AFTER method } } end end end
You need to login to post a comment.
