title: Meta-programming: output method body as text
body: <p>I'm dynamically defining a method in a module, and I'd like to check that once the method is bound to a class instance that the body of the method is what I'm expecting.  Is there a way to output (as text) of the body of a method?</p>
  
  <p>Module <code>controller_mixins.rb</code>:</p>
  
  <pre><code>module ControllerMixin
  
    instance_eval "def search_by_vendor (*args) \n" \
      " @#{self.class.name.sub(/Controller/, '').tableize} = #{self.class.name.sub(/Controller/, '')}.find_all_by_vendor_id(params[:vendor_id])  \n"\
      "respond_to do |format| \n" \
      " format.html { render :template=&gt;'/#{self.class.name.sub(/Controller/, '').tableize}/index',  :layout=&gt;'vendor_info'} \n" \
      " format.xml  { render :xml =&gt; @#{self.class.name.sub(/Controller/, '').tableize} } \n" \
      "end \n"\
    "end \n"
  
  end
  </code></pre>
  
  <p>class being mixed with:</p>
  
  <pre><code>class VendorOrdersController &lt; ApplicationController
    # GET /vendor_orders
    # GET /vendor_orders.xml
    require 'controller_mixins'
    include ControllerMixin
   &lt;rest of class&gt;
  </code></pre>
  
  <p>So I'd like to see the implementation of the mixin when applied to <code>VendorOrdersController</code>
  probably via <code>script/console</code> for convenience.</p>
  
  <p>UPDATE:  Per @~/ I saved the string to a variable and <code>puts</code>'d it.  That worked perfectly.  Which brought to light an error in my code (the reason I wanted to see the code in the first place).  Code below is much better, and works as expected.</p>
  
  <pre><code>module ControllerMixin
  
    def self.included(mod)
       method_body = "def search_by_vendor \n" \
        " @#{mod.name.sub(/Controller/, '').tableize} = #{mod.name.sub(/Controller/, '')}.find_all_by_vendor_id(params[:vendor_id])  \n"\
        "respond_to do |format| \n" \
        " format.html { render :template=&gt;'/#{mod.name.sub(/Controller/, '').tableize}/index',  :layout=&gt;'vendor_info'} \n" \
        " format.xml  { render :xml =&gt; @#{mod.name.sub(/Controller/, '').tableize} } \n" \
        "end \n"\
      "end \n" 
  
      puts method_body
      mod.class_eval(method_body)
    end
  
  end
  </code></pre>