code-snipplet|| BeforeAndAfterMethod


require "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




BEFORE DISPLAY
== MESSAGE ==
AFTER DISPLAY





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



http://snipplr.com/view/17292/beforeandafter/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值