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/

你可能感兴趣的:(Ruby,UP)