Your Ad Here

Posted By

c00lryguy on 07/21/09


Tagged

ruby


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


BeforeAndAfter


 / Published in: Ruby
 

Allows you to create before and after methods in a class

Example
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
Outputs
BEFORE DISPLAY
== MESSAGE ==
AFTER DISPLAY
before_and_after.rb

 

  1. module BeforeAndAfter
  2. # This extends the class that includes BeforeAndAfter with the methods in ClassMethods
  3. def self.included(base)
  4. base.extend(ClassMethods)
  5. end
  6.  
  7. module ClassMethods
  8. def use_method *methods
  9. methods.each { |method|
  10. # Set up the before and after variables
  11. before_method = "before_#{method.to_s}".to_sym
  12. after_method = "after_#{method.to_s}".to_sym
  13. # Unbind the original, before, and after methods
  14. unbinded_before_method = instance_method( before_method )
  15. unbinded_method = instance_method( method )
  16. unbinded_after_method = instance_method( after_method )
  17. # Define the before and after methods if they don't already exist
  18. define_method( before_method ) unless self.method_defined?( before_method )
  19. define_method( after_method ) unless self.method_defined?( after_method )
  20. # Redefines the method to run the before and after methods
  21. define_method( method ) {
  22. unbinded_before_method.bind( self ).call # Bind the unbinded BEFORE method
  23. unbinded_method.bind( self ).call # Bind the original method
  24. unbinded_after_method.bind( self ).call # Bind the unbinded AFTER method
  25. }
  26. }
  27. end
  28. end
  29. end

Report this snippet  

You need to login to post a comment.