Ruby怎么实现Python的Decorator

今天下午和Wilbeibi讨论了下Python的Decorator,我觉得挺有趣。有点以前写Rails时候的Controller filter或者Active Record Callbacks的意思。所以晚上回来我把Python的Decorator简单了看了一下,也搜索了下看看Ruby有没有类似的功能,顺便花了点时间用Ruby写了个原型。有段时间没写Ruby了,没那么顺手了。

好了,夜深了,要睡觉了。

module Decorator
  def log_around(func)
    class_eval <<-DEC
      alias_method :old_#{func}, :#{func}
      def #{func}(*args, &blk)
        lambda do |*a, &b|
          # do what you want to do here
          puts "----- start greeting -----"
          old_#{func}(*a, &b)
          # and here
          puts "----- end greeting -----"
        end.call(*args, &blk)
      end
    DEC
  end

  def close_at_end(func)
    class_eval <<-DEC
      alias_method :old_#{func}, :#{func}
      def #{func}(*args, &blk)
        lambda do |*a, &b|
          old_#{func}(*a, &b)
          puts "----- close at end  -----"
        end.call(*args, &blk)
      end
    DEC
  end
end

class Test
  extend Decorator

  def greeting(name)
    puts "Hello, I'm #{name}"
  end
  log_around(:greeting)


  def edit_file
    puts "open file ..."
    puts "writing file ..."
  end
  close_at_end(:edit_file)

end

Test.new.greeting("yanguango")
Test.new.edit_file