title: Ruby/Rails: Prepend, append code to all methods
body: <p>I wrote a small benchmarking Class for testing my code doing development. At the moment I have to add the Class to the beginning and end of every method. Is it posible to prepend, append on the fly, so that I don't have to clutter my code?</p>
  
  <pre><code>class ApplicationController    
      before_filter :init_perf
      after_filter :write_perf_results_to_log!
  
      def init_perf
        @perf ||= Perf.new
      end
  
      def write_perf_results_to_log!
        @perf.results
      end
  end
  
  class Products &lt; ApplicationsController    
      def foo      
        @perf.log(__methond__.to_s)
        caculation = 5 *4
        @perf.write! 
      end
  
      def bar      
        @perf.log(__methond__.to_s)
        caculation = 1 / 5
        @perf.write! 
      end
  end
  </code></pre>
  
  <p>This is the Perf class. It is located in the services folder.</p>
  
  <pre><code>class Perf
    def initialize
      @results = []
    end
  
    def log(note)
      @start = Time.now
      @note = note
    end
  
    def write!
      if @results.find {|h| h[:note] == @note } # Update :sec method exists in results 
        @results.select { |h| h["note"] == @note; h[":sec"] = (Time.now - @start).round(3) }
      else # Add new Hash to results
        @results &lt;&lt; { :note =&gt; @note, :sec =&gt; (Time.now - @start).round(3) }
      end
    end
  
    def results
      content = "
      PERFORMANCE STATISTICS!
      "
      @results.each do |r|
        content += r[:note] + "   " + r[:sec].to_s + "
        "
      end
      content += "
      "
      Rails.logger.info content
    end
  end
  </code></pre>