<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: metaprogramming code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 26 Jul 2008 19:38:11 GMT</pubDate>
    <description>DZone Snippets: metaprogramming code</description>
    <item>
      <title>Wrap all methods of an object</title>
      <link>http://snippets.dzone.com/posts/show/4087</link>
      <description>Given an existing object "obj", wraps all of its methods.  In this case, the wrapper prints a log of the method invocation, and the call stack of the call, but you can modify it to do anything...&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;virtual_class = class &lt;&lt;obj; self; end&lt;br /&gt;&lt;br /&gt;virtual_class.class_eval {&lt;br /&gt;  obj.methods.each { |method|&lt;br /&gt;    the_alias = method.gsub(/([^?]+)(\??)/, "\\1_orig\\2").to_sym&lt;br /&gt;    alias_method the_alias, method&lt;br /&gt;&lt;br /&gt;    define_method(method) { |*args|&lt;br /&gt;        args_str = args.map { |a| a.inspect }.join(", ")&lt;br /&gt;        unless method == "to_s"&lt;br /&gt;          puts "#{self.inspect_orig}.#{method}(#{args_str}) called from #{caller.inspect}"&lt;br /&gt;        end&lt;br /&gt;        self.send_orig(the_alias, *args)&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 31 May 2007 23:23:12 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4087</guid>
      <author>haberman (Joshua Haberman)</author>
    </item>
  </channel>
</rss>
