<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tender Lovemaking &#187; rails</title>
	<atom:link href="http://tenderlovemaking.com/category/rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://tenderlovemaking.com</link>
	<description>The act of making love, tenderly.</description>
	<lastBuildDate>Sun, 15 Jan 2012 04:36:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Connection Management in ActiveRecord</title>
		<link>http://tenderlovemaking.com/2011/10/20/connection-management-in-activerecord/</link>
		<comments>http://tenderlovemaking.com/2011/10/20/connection-management-in-activerecord/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 19:14:53 +0000</pubDate>
		<dc:creator>Aaron Patterson</dc:creator>
				<category><![CDATA[computadora]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://tenderlovemaking.com/?p=566</guid>
		<description><![CDATA[OMG! Happy Thursday! I am trying to be totally enthusiastic, but the truth is that I have a cold, so there will be fewer uppercase letters and exclamation points than usual. Anyway, I want to talk about database connection management in ActiveRecord. I am not too pleased with its current state of affairs. I would [...]]]></description>
			<content:encoded><![CDATA[<p>OMG! Happy Thursday!  I am trying to be totally enthusiastic, but the truth is that I have a cold, so there will be fewer uppercase letters and exclamation points than usual.</p>
<p>Anyway, I want to talk about database connection management in ActiveRecord.  I am not too pleased with its current state of affairs.  I would like to describe how ActiveRecord connection management works today, how I think it <em>should</em> work, and steps towards fixing the current system.</p>
<p><strong>TL;DR: database connection API in ActiveRecord should be more similar to File API</strong></p>
<h2>Thinking in terms of files</h2>
<p>It&#8217;s convenient to think of our database connection as a file.  Dealing with files is very common.  When we work with files, the basic sequence goes something like this:</p>
<ul>
<li>Open the file</li>
<li>Do some work on the file handle</li>
<li>Close the file</li>
</ul>
<p>We&#8217;re very used to doing these steps when dealing with files.  Typically our code will look something like this:</p>
<pre class="brush: ruby; title: ; notranslate">
File.open('somefile.txt', 'wb') do |fh| # Open the file
  fh.write &quot;hello world&quot;                # Do some work with the file
end                                     # Close file when block returns
</pre>
<p>We don&#8217;t want to share open files among threads because dealing with synchronization around reading and writing to the file is too difficult (and time consuming).  So maybe we&#8217;ll store the handle in a thread local or something until we&#8217;re ready to close it.</p>
<p>Our basic requirements for dealing with a database connection are essentially the same as when dealing with files.  We need to open our database connection, do some work with the connection (send and receive queries), and close the connection.  We have these similarities, yet the API for dealing with database connections in ActiveRecord is vastly different.  Let&#8217;s look at how each of these steps are performed in ActiveRecord today.</p>
<h2>Opening a connection</h2>
<p>Opening a connection to the database is very easy.  First we configure ActiveRecord with the database specification, then we call <code>connection</code> to actually get back a database handle:</p>
<pre class="brush: ruby; title: ; notranslate">
ActiveRecord::Base.establish_connection(
  :adapter  =&gt; &quot;sqlite&quot;,
  :database =&gt; &quot;path/to/dbfile&quot;)

connection_handle = ActiveRecord::Base.connection
</pre>
<p>The main difference between this API and the File API is that we&#8217;ve separated the connection specification from actually opening the connection.  In the case of opening a file, we call <code>open</code> along with a &#8220;specification&#8221; which includes the file name and how we want to open it.  In this case, we&#8217;ve separated the two; essentially storing the specification in a global place, then opening the connection later.</p>
<p>This leads to two questions:</p>
<ol>
<li>Where is the specification stored?</li>
<li>When I call <code>connection</code>, what specification is used?</li>
</ol>
<p>The answer to the first question can be found by reading the <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb#L57-91"><code>establish_connection</code> method</a>.  Specifically if we look at <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb#L63">line 63</a> we&#8217;ll find a clue.  Since this method is a class method, the call to <code>name</code> returns the <em>class name of the recipient</em>.  This name (along with our actual spec) is passed in to the connection handler object.  If we jump through a few more layers of indirection, we&#8217;ll find that what we have is essentially a one to one mapping of <em>class name to connection specification</em>.</p>
<p>Armed with this information, we can tackle the second question.  If we look at the <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb#L114-116">implementation of <code>connection</code></a>, it calls <code>retrieve_connection</code> on itself, which calls <code>retrieve_connection</code> on the connection handler with itself.  A few more method calls later, and we see that each ActiveRecord subclass <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb#L432-437">walks up the inheritance tree looking for a connection</a>:</p>
<pre class="brush: ruby; title: ; notranslate">
def retrieve_connection_pool(klass)
  pool = @connection_pools[klass.name]
  return pool if pool
  return nil if ActiveRecord::Base == klass
  retrieve_connection_pool klass.superclass
end
</pre>
<p>If we read this code carefully, we&#8217;ll notice that not only are connection specifications mapped to classes so are database connections!</p>
<h3>Why is this bad?</h3>
<p>This behavior smells bad to me.  The reason is because we&#8217;re tightly coupling classes along with database connections when really this relationship doesn&#8217;t need to exist.</p>
<h3>How can it be improved?</h3>
<p>If this tight coupling is removed, the complexity of ActiveRecord can be reduced and at the same time increasing the features available!  The way we can reduce this coupling is by passing the connection specification to the method that actually opens the connection.  Specifications can be stored on each class as a <em>convenience</em>, but nothing more.</p>
<p>What if opening a connection looked more like this?</p>
<pre class="brush: ruby; title: ; notranslate">
spec = ActiveRecord::Base.specificiation
ActiveRecord::ConnectionPool.open(spec) do |conn|
  ...
end
</pre>
<p>We could maintain the current behavior by storing specifications on each class, but eliminate the coupling between connection and class.  We would be able to delete all of the code that looks up connections by class hierarchy, and open the doors to having features like this:</p>
<pre class="brush: ruby; title: ; notranslate">
spec = database_a
ActiveRecord::ConnectionPool.open(spec) do |conn|
  User.find_all
end

spec = database_b
ActiveRecord::ConnectionPool.open(spec) do |conn|
  User.find_all
end
</pre>
<h2>Working with the connection</h2>
<p>Working with our connection should remain the same.  We have one place to retrieve our connection and work with it.  Woo!</p>
<h2>Dealing with thread safety</h2>
<p>Sharing open file handles among threads probably isn&#8217;t a good idea and the same can be said about open database connections.  So how does ActiveRecord keep connections localized to one thread?  If we jump through many, many, method calls, we&#8217;ll find where the connection is actually checked out of the connection pool.  It is <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb#L156-163">here we see how thread safety is handled</a>:</p>
<pre class="brush: ruby; title: ; notranslate">
# Retrieve the connection associated with the current thread, or call
# #checkout to obtain one if necessary.
#
# #connection can be called any number of times; the connection is
# held in a hash keyed by the thread id.
def connection
  @reserved_connections[current_connection_id] ||= checkout
end
</pre>
<p>A hash is kept where the key is the <code>current_connection_id</code>.  The implementation of <code>current_connection_id</code> looks up the current id.  If the id isn&#8217;t set, it sets it to the object id of the current thread:</p>
<pre class="brush: ruby; title: ; notranslate">
def current_connection_id #:nodoc:
  ActiveRecord::Base.connection_id ||= Thread.current.object_id
end
</pre>
<p>Next we look at the implementation of <code>connection_id</code> to find that it just <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb#L118-124">gets and sets a thread local</a>:</p>
<pre class="brush: ruby; title: ; notranslate">
def connection_id
  Thread.current['ActiveRecord::Base.connection_id']
end

def connection_id=(connection_id)
  Thread.current['ActiveRecord::Base.connection_id'] = connection_id
end
</pre>
<p>These methods ensure that we have a one to one relationship of open connection and thread.</p>
<h2>Closing the connection</h2>
<p>Finally we reach our last step: closing the connection.  How many of you have closed your connection to the database in ActiveRecord?  My guess is that it&#8217;s very few.  I think the reason people don&#8217;t typically close their connections with ActiveRecord is twofold.  One, you don&#8217;t have to because it just does it for you, and two, the API to close a particular connection is pretty convoluted.</p>
<p>So how is the connection closed today?  There are two ways, the easy way and the hard way.</p>
<h3>The easy way</h3>
<p>The easy way is good enough in a non-threaded application.  A rack middleware <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb#L461-467">clears out all of the connections at the end of the request</a>.  The source for <code>clear_active_connections!</code> is pretty simple.  For each connection pool in the system (remember it&#8217;s one pool per AR class and connection spec), release that connection:</p>
<pre class="brush: ruby; title: ; notranslate">
# Returns any connections in use by the current thread back to the pool,
# and also returns connections to the pool cached by threads that are no
# longer alive.
def clear_active_connections!
  @connection_pools.each_value {|pool| pool.release_connection }
end
</pre>
<p>Each pool releases the connection it has using the <code>current_connection_id</code> (which happens to be the current thread id):</p>
<pre class="brush: ruby; title: ; notranslate">
# Signal that the thread is finished with the current connection.
# #release_connection releases the connection-thread association
# and returns the connection to the pool.
def release_connection(with_id = current_connection_id)
  conn = @reserved_connections.delete(with_id)
  checkin conn if conn
end
</pre>
<p>Not bad.  But what if our system has multiple threads?</p>
<h3>The hard way</h3>
<p>Believe it or not, the connection pool in ActiveRecord will check in connections in the checkout method.  Let me say that again: the checkout method checks in connections and checks out connections.  If you&#8217;re not facepalming yet, let&#8217;s look at a small part of the checkout method:</p>
<pre class="brush: ruby; title: ; notranslate">
@queue.wait(@timeout)

if(@checked_out.size &lt; @connections.size)
  next
else
  clear_stale_cached_connections!
  if @size == @checked_out.size
    raise ConnectionTimeoutError, &quot;could not obtain a database connection#{&quot; within #{@timeout} seconds&quot; if @timeout}. The max pool size is currently #{@size}; consider increasing it.&quot;
  end
end
</pre>
<p>This bit of the checkout method is not called unless our connection pool has become full.  First we wait for other threads to check in their connection.  While we&#8217;re waiting, if other threads checked in their connection, the first branch of the if statement executes, and a connection is returned.  If no threads have checked in their connection, we call <code>clear_stale_cached_connections!</code>:</p>
<pre class="brush: ruby; title: ; notranslate">
def clear_stale_cached_connections!
  keys = @reserved_connections.keys - Thread.list.find_all { |t|
    t.alive?
  }.map { |thread| thread.object_id }
  keys.each do |key|
    checkin @reserved_connections[key]
    @reserved_connections.delete(key)
  end
end
</pre>
<p>This method walks through every thread in your system, looking for connections that were allocated to threads that no longer exist.  Then it checks in connections associated with those dead threads.  Since there is really no easy way for users to check in their own connections, this is actually a common code path for systems that use threads.</p>
<h3>Why is this bad?</h3>
<p>It should be pretty clear why this behavior is bad.  Walking through every thread in the system, and asking if it&#8217;s alive isn&#8217;t very cheap.  Even worse is that we&#8217;re coupling ourselves to the threading system.  We cannot change the connection pool to work with other concurrency solutions (like Fibers) because those solutions may not give us the introspection we need to perform this operation!</p>
<p>But really, this is treating a symptom.  The real problem is that checking in connections is too difficult, so people don&#8217;t do it.</p>
<h3>How can we fix this?</h3>
<p>I think the best solution for this is to mimic the File API.  If we do this, it will become natural for people dealing with the database connection to actually close the connection.</p>
<p>We should make <code>ActiveRecord::Base.connection</code> consult a thread local.  That thread local is set in the rack middleware where the connection is opened.  If someone creates a new thread, they must populate that thread local, and close the connection at the end of the thread.</p>
<p>Simplified, our middleware would become something like this:</p>
<pre class="brush: ruby; title: ; notranslate">
class ConnectionManagement
  def call env
    spec       = ActiveRecord::Base.spec
    connection = ActiveRecord::ConnectionPool.open spec
    ActiveRecord::Base.connection = connection

    @app.call env

    connection.close
  end
end
</pre>
<p>When people create a new thread, it would look something like this:</p>
<pre class="brush: ruby; title: ; notranslate">
Thread.new do
  spec = ActiveRecord::Base.spec
  ActiveRecord::ConnectionPool.open(spec) do |connection|
    ActiveRecord::Base.connection = connection

    # do some stuff
  end
end
</pre>
<h3>What does this buy us?</h3>
<p>This buys us two important things: simple connection pool management, and freedom of choice on our concurrency model.</p>
<h2>omg the end.</h2>
<p>I hope I&#8217;ve convinced you that by simply learning to treat our database connection like a file, we can reduce code complexity and at the same time increase the features available.  I think I can add this feature to Rails 3.2 and mostly maintain backwards compatibility.  I think we can keep 100% backwards compatibility if we add some sort of flag like <code>config.i_suck_and_will_not_close_my_database_connections = true</code> or, <code>config.my_app_is_awesome = true</code>.</p>
<p>Anyway, I&#8217;m totally sick and I&#8217;ll stop blllluuurrrrggghhhing now.</p>
<p>&lt;3 &lt;3 &lt;3 &lt;3 &lt;3</p>
]]></content:encoded>
			<wfw:commentRss>http://tenderlovemaking.com/2011/10/20/connection-management-in-activerecord/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Rack API is awkward</title>
		<link>http://tenderlovemaking.com/2011/03/03/rack-api-is-awkward/</link>
		<comments>http://tenderlovemaking.com/2011/03/03/rack-api-is-awkward/#comments</comments>
		<pubDate>Thu, 03 Mar 2011 19:24:59 +0000</pubDate>
		<dc:creator>Aaron Patterson</dc:creator>
				<category><![CDATA[computadora]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://tenderlovemaking.com/?p=522</guid>
		<description><![CDATA[TL;DR: Rack API is poor when you consider streaming response bodies. ZOMG!!!! HAPPY THURSDAY!!!! Maybe I shouldn&#8217;t be so excited now. I want to talk about stuff I&#8217;ve been working on in Rails 3.1, and problems I&#8217;m encountering today. I want to use this blllurrrggghhh blog post to talk through through the problems I&#8217;ve been [...]]]></description>
			<content:encoded><![CDATA[<p><strong>TL;DR: Rack API is poor when you consider streaming response bodies.</strong></p>
<p>ZOMG!!!!  HAPPY THURSDAY!!!!  Maybe I shouldn&#8217;t be so excited now.  I want to talk about stuff I&#8217;ve been working on in Rails 3.1, and problems I&#8217;m encountering today.  I want to use this blllurrrggghhh blog post to talk through through the problems I&#8217;ve been having, and to share the pain with others.</p>
<h2>Pie is delicious!</h2>
<p>One feature that would be useful to add to Rails is having a streaming response body.  When Rails processes a response, the entire response is buffered in memory before it can be sent to the user.  Some information like Content Length (among other things) is derived, and the response is sent.</p>
<p>Sometimes buffering a response is less than ideal.  It would be nice if we could send the head tag along with any css or script includes to the browser as quickly as possible.  Then the browser can download external resources while we&#8217;re still processing data on the server.  If this were possible, total response time may remain the same, but the time to first byte would be decreased and the page would load faster as external resource can be downloaded in parallel.</p>
<p>This feature sounds great, but there are many things to think about before it can be implemented.  We need to support infinite streams, chunked encoding, prevent header manipulation, ensure database connections, blah, blah blah.</p>
<h2>Rack interface</h2>
<p>I&#8217;m getting ahead of myself.  Before we get to our ultimate &#8220;pie in the sky&#8221; streaming solution, let&#8217;s take a look at the Rack API.  Rack defines an interface for writing web applications.  A rack handler must respond to <code>call</code> which takes one parameter, the request environment.  <code>call</code> must return a three item list of:</p>
<ul>
<li>Response code</li>
<li>Headers</li>
<li>Body</li>
</ul>
<p>The response code should be a number (like 200), the headers are a hash (like { &#8216;X-Omg&#8217; => &#8216;hello!&#8217; }).  The body must respond to <code>each</code> and take a block.  The body must yield a string to the block, and the string will be output to the client.  Optionally, the body may respond to <code>close</code>, and rack will call <code>close</code> when output is complete.</p>
<h2>An Example Rack application</h2>
<p>Let&#8217;s write an example application.  Our sample application will simulate an ERb page.  We&#8217;ll add some <code>sleep</code> statements to simulate work happening during the ERb rendering process:</p>
<pre class="brush: ruby; title: ; notranslate">
class FooApplication
  class ErbPage
    def to_a
      head = &quot;the head tag&quot;
      sleep(2)
      body = &quot;the body tag&quot;
      sleep(2)
      [head, body]
    end
  end

  def call(env)
    [200, {}, ErbPage.new.to_a]
  end
end
</pre>
<p>For the purposes of demonstration, we&#8217;ll be using a fake implementation of rack:</p>
<pre class="brush: ruby; title: ; notranslate">
class FakeRack
  def serve(application)
    status, headers, body = application.call({})
    p :status  =&gt; status
    p :headers =&gt; headers

    body.each do |string|
      p string
    end

    body.close if body.respond_to?(:close)
  end
end
</pre>
<p>If we feed our application through FakeRack like this:</p>
<pre class="brush: ruby; title: ; notranslate">
app  = FooApplication.new
rack = FakeRack.new

rack.serve app
</pre>
<p>We&#8217;ll see output from the rack application, and the total program run time is about 4 seconds:</p>
<pre class="brush: ruby; title: ; notranslate">
$ time ruby foo.rb
{:status=&gt;200}
{:headers=&gt;{}}
&quot;the head tag&quot;
&quot;the body tag&quot;

real    0m4.008s
user    0m0.003s
sys     0m0.003s
</pre>
<p>Great!  So far, no problem.  Why don&#8217;t we add a middleware to time how long the response takes.</p>
<h2>Rack Middleware</h2>
<p>Rack Middleware is simply another Rack application.  With Rack, we set up a linked list of middleware that eventually point to the real application.  We give the head of the linked list to Rack, Rack calls <code>call</code> on the head of the list, and it is the list&#8217;s responsibility to call <code>call</code> on it&#8217;s link.</p>
<p>Here, we&#8217;ll write a Rack middleware to measure how long the &#8220;ERb render&#8221; takes and add a header indicating the response time.</p>
<pre class="brush: ruby; title: ; notranslate">
class ResponseTimer
  def initialize(app)
    @app = app
  end

  def call(env)
    now                        = Time.now
    status, headers, body      = @app.call(env)
    headers['X-Response-Took'] = Time.now - now

    [status, headers, body]
  end
end
</pre>
<p>When we construct the ResponseTimer, we pass it the real application.  Then we pass the response timer instance to rack:</p>
<pre class="brush: ruby; title: ; notranslate">
app   = FooApplication.new
timer = ResponseTimer.new app
rack  = FakeRack.new

rack.serve timer
</pre>
<p>When rack calls <code>call</code> on the response timer, it records the current time, then calls <code>call</code> on the real application.  When the real application returns, the response timer then adds a header with the time delta.  The output of this program will look like this:</p>
<pre class="brush: ruby; title: ; notranslate">
$ time ruby foo.rb
{:status=&gt;200}
{:headers=&gt;{&quot;X-Response-Took&quot;=&gt;3.999937}}
&quot;the head tag&quot;
&quot;the body tag&quot;

real    0m4.010s
user    0m0.004s
sys     0m0.004s
</pre>
<h2>Speeding up our response time</h2>
<p>We&#8217;ve noticed a problem with our Rack application.  When a client connects, it takes 4 seconds before they receive any data!  It would be nice if we could feed our client the head tag ASAP so they can download external resources.</p>
<p>We know that Rack will call <code>each</code> and (depending on your webserver) immediately send data to the client.  Rather than computing values in ERb ahead of time, we&#8217;ll compute them when Rack asks for them (when <code>each</code> is called).</p>
<p>Let&#8217;s refactor the ERb page to be lazy about calculating values:</p>
<pre class="brush: ruby; title: ; notranslate">
class FooApplication
  class ErbPage
    def each
      head = &quot;the head tag&quot;
      yield head

      sleep(2)

      body = &quot;the body tag&quot;
      yield body

      sleep(2)
    end
  end

  def call(env)
    [200, {}, ErbPage.new]
  end
end
</pre>
<p>Now no values are calculated until rack calls <code>each</code> on our body.  If we run the program, we&#8217;ll see output from the application more quickly than before.</p>
<p>However, the output is somewhat strange:</p>
<pre class="brush: ruby; title: ; notranslate">
$ time ruby foo.rb
{:status=&gt;200}
{:headers=&gt;{&quot;X-Response-Took&quot;=&gt;1.1e-05}}
&quot;the head tag&quot;
&quot;the body tag&quot;

real    0m4.032s
user    0m0.027s
sys     0m0.016s
</pre>
<p>The time command reports that our response was about 4 seconds.  But our response header says that the response took nearly 0 seconds!  Why is this?</p>
<p>If we look closely at our timer middleware, we can see it is only timing <em>how long it took for <code>call</code> to return</em>.</p>
<p>We cannot guarantee that <em>any</em> processing happened during the <code>call</code> method.</p>
<p>Let me say that again:</p>
<p><strong>We cannot guarantee that <em>any</em> processing happened during the <code>call</code> method.</strong></p>
<p>We wanted our response timer to time how long the ERb took to render, but really it is just timing how long the <code>call</code> method took.</p>
<h2>ZOMG HOW FIX?!?</h2>
<h3>Iterating over the body</h3>
<p>One way to fix is to iterate over the body.  If the timer iterates over the body, then we can calculate the real time:</p>
<pre class="brush: ruby; title: ; notranslate">
class ResponseTimer
  def initialize(app)
    @app = app
  end

  def call(env)
    now                        = Time.now
    status, headers, body      = @app.call(env)

    newbody = []
    body.each { |str| newbody &lt;&lt; str }
    headers['X-Response-Took'] = Time.now - now

    [status, headers, newbody]
  end
end
</pre>
<p>But this solution is no good!  Our response timer now buffers the response, and our client ends up waiting for 4 seconds before they get any data.</p>
<p>We know that Rack calls <code>close</code> on the body after it&#8217;s done processing the request.  Why don&#8217;t we try hooking on that method?</p>
<h3>Introducing a Proxy Object</h3>
<p>One way we can hook on to the close method is by wrapping the response body in a proxy object.  Then we can intercept calls made on the body and perform any work we need done:</p>
<pre class="brush: ruby; title: ; notranslate">
class ResponseTimer
  class TimerProxy
    def initialize(body)
      @now     = Time.now
      @body    = body
    end

    def close
      @body.close if @body.respond_to?(:close)

      $stderr.puts({'X-Response-Took' =&gt; (Time.now - @now)})
    end

    def each(&amp;block)
      @body.each(&amp;block)
    end
  end

  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, body = @app.call(env)

    [status, headers, TimerProxy.new(body)]
  end
end
</pre>
<p>Wow!  Suddenly our middleware is not so simple.  This proxy solution is sub-optimal for a few reasons.  We&#8217;re required to make a new object for every request, and our proxy object will add another stack frame between calls from rack to the response body.  Even worse, every middleware that needs to do work after the response is finished must define this proxy object.</p>
<p>This solution does get the job done.  If we look at the output from the program, we&#8217;ll see that the TimerProxy in fact measures ERb processing time correctly:</p>
<pre class="brush: ruby; title: ; notranslate">
$ time ruby foo.rb
{:status=&gt;200}
{:headers=&gt;{}}
&quot;the head tag&quot;
&quot;the body tag&quot;
{&quot;X-Response-Took&quot;=&gt;4.000268}

real    0m4.044s
user    0m0.029s
sys     0m0.015s
</pre>
<p>Diligent readers will note that the response time is no longer part of the response headers.  This is because when the body is flushed, the headers must be flushed too.  We no longer have the opportunity to add extra headers when <code>each</code> is called on the body.</p>
<p>Our solution isn&#8217;t <em>too bad</em>, but it actually isn&#8217;t complete.  The full awkwardness of this API along with a complete solution can actually be felt (and read) <a href="https://github.com/rack/rack/blob/master/lib/rack/lock.rb">in the Rack source itself</a>.</p>
<h3>Lady Gaga Solution</h3>
<p>Another possible solution is to decorate the body using a module.  We can define a module, then simply call <code>extend</code> on the body with the module:</p>
<pre class="brush: ruby; title: ; notranslate">
class ResponseTimer
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, body      = @app.call(env)
    body.extend(Module.new {
      now = Time.now

      define_method(:close) do
        super if defined?(super)

        $stderr.puts({'X-Response-Took' =&gt; (Time.now - now)})
      end
    })

    [status, headers, body]
  end
end
</pre>
<p>The body is extended with an anonymous module.  During module definition, the time is recorded.  We use <code>define_method</code> because it uses a lambda which will keep a reference to the previously calculated time.  In the <code>close</code> method, we call super if it&#8217;s defined, then output our time.</p>
<p>This example also works, but has a few downsides.  It is different than previous examples because we are timing <em>only</em> the ERb rendering and not <code>call</code> plus ERb rendering.  Using this solution, we&#8217;re required to create a new module on every request, and also break method caching on every request.  Similar to the proxy object solution, we must create a new module and extend for every middleware that must to processing after the response is finished.</p>
<h2>ZOMG YOUR EXAMPLE IS CONTRIVED</h2>
<p>Yup.  But I merely simplified a real world problem.  As I mentioned earlier, you can see the awkwardness of this API <a href="https://github.com/rack/rack/blob/master/lib/rack/lock.rb">in rack</a>.</p>
<p>But now that we know about this problem, we can identify middleware that will break streaming responses.  For example, Rails defines a middleware <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb#L407-421">that checks connections back in to the connection pool</a>.  If our ERb in Rails was streaming, we would lose the database connection during ERb render.  The same is true with the <a href="https://github.com/rails/rails/blob/master/activerecord/lib/active_record/query_cache.rb#L30-34">query cache in active record</a>.  Surely, these cannot be the only middleware that will break when a streaming body is used!</p>
<h2>Lifecycle hooks</h2>
<p>I think a good solution to this problem would be if Rack provided lifecycle hooks.  A Place where we can say &#8220;run this when the response is done&#8221;.  We can define something like that today using middleware:</p>
<pre class="brush: ruby; title: ; notranslate">
class EndOfLife
  attr_reader :callbacks

  def initialize(app)
    @app       = app
    @callbacks = []
  end

  def call(env)
    status, headers, body = @app.call(env)
    body.extend(Module.new {
      attr_accessor :eol

      def close
        super if defined?(super)
        eol.callbacks.each { |cb| cb.call }
      end
    })
    body.eol = self

    [status, headers, body]
  end
end

app = FooApplication.new
eol = EndOfLife.new app
eol.callbacks &lt;&lt; lambda { puts &quot;it finished!&quot; }

rack  = FakeRack.new

rack.serve eol
</pre>
<p>This keeps us from defining many proxy objects or module extensions during a response.  We only define one module extension, and hook any &#8220;end of life&#8221; hooks on to this instance.  The downside is that we cannot guarantee the position of this middleware in the middleware linked list.  That means that the &#8220;end of life&#8221; middleware may not actually execute at the end of the response!</p>
<h2>A &#8220;real&#8221; solution</h2>
<p>Rack&#8217;s interface is simple, and I like that.  The simplicity is attractive, but the API seems to fall on it&#8217;s face when we start talking about streaming web servers.  If I remember correctly, Apache 1.0 modules suffered the same problems that Rack is presenting us today.  Maybe we should look at Apache 2.0 <a href="http://www.apachetutor.org/dev/brigades">buckets and filters</a> and design our API using patterns from a project that has already solved this problem.</p>
<h2>ZOMG I AM TIRED OF TYPING!!</h2>
<p>I&#8217;m not happy with any of the solutions I&#8217;ve presented.  All of them have downsides that I find unattractive.  We can live with the downsides, but life will suck.  If any of you dear readers have better solutions for me, I am all ears!</p>
<p>Thanks for listening, and HAVE A GREAT DAY!!!!</p>
<p>&lt;3 &lt;3 &lt;3 &lt;3 &lt;3</p>
<p><strong>Edit:</strong> I just noticed that Rack contains a &#8220;timer&#8221; middleware similar to the one I&#8217;ve implemented in this blog post.  You can view the broken middleware <a href="https://github.com/rack/rack/blob/master/lib/rack/runtime.rb">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://tenderlovemaking.com/2011/03/03/rack-api-is-awkward/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Easy Markup Validation</title>
		<link>http://tenderlovemaking.com/2009/06/12/easy-markup-validation/</link>
		<comments>http://tenderlovemaking.com/2009/06/12/easy-markup-validation/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 00:24:01 +0000</pubDate>
		<dc:creator>Aaron Patterson</dc:creator>
				<category><![CDATA[computadora]]></category>
		<category><![CDATA[nokogiri]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://tenderlovemaking.com/?p=302</guid>
		<description><![CDATA[I wanted a test helper that would assert that my XHTML was valid XHTML. So I wrote one and called it &#8220;markup_validity&#8220;. You can use it too, and I will show you how. First, install the gem: $ sudo gem install markup_validity Then, use it in your tests: Oh. You use RSpec? It supports that [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted a test helper that would assert that my XHTML was valid XHTML.  So I wrote one and called it &#8220;<a href="http://github.com/tenderlove/markup_validity/tree/master">markup_validity</a>&#8220;.  You can use it too, and I will show you how.</p>
<p>First, install the gem:</p>
<pre>
  $ sudo gem install markup_validity
</pre>
<p>Then, use it in your tests:</p>
<pre class="brush: ruby; title: ; notranslate">
require 'test/unit'
require 'rubygems'
require 'markup_validity'

class ValidHTML &lt; Test::Unit::TestCase
  def test_i_can_has_valid_xhtml
    assert_xhtml_transitional xhtml_document
  end
end
</pre>
<p>Oh.  You use RSpec?  It supports that too:</p>
<pre class="brush: ruby; title: ; notranslate">
require 'rubygems'
require 'markup_validity'

describe &quot;my XHTML document&quot; do
  it &quot;can has transitional xhtml&quot; do
    xhtml_document.should be_xhtml_transitional
  end
end
</pre>
<p>Debugging invalid markup can be a pain.  MarkupValidity tries to give you helpful errors to make your life easier.  Say you have an invalid piece of XHTML like this:</p>
<pre class="brush: plain; title: ; notranslate">
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
  &lt;head&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;p&gt;
      &lt;p&gt;
        Hello
      &lt;/p&gt;
    &lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The error output from MarkupValidity will be this:</p>
<pre class="brush: plain; title: ; notranslate">
.Error on line: 2:
Element 'head': Missing child element(s). Expected is one of ( script, style, meta, link, object, isindex, title, base ).

1: &lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
2:   &lt;head&gt;
3:   &lt;/head&gt;
4:   &lt;body&gt;
5:     &lt;p&gt;

Error on line: 6:
Element 'p': This element is not expected. Expected is one of ( a, br, span, bdo, object, applet, img, map, iframe, tt ).

5:     &lt;p&gt;
6:       &lt;p&gt;
7:         Hello
8:       &lt;/p&gt;
9:     &lt;/p&gt;
</pre>
<p>MarkupValidity provides a few assertions for test/unit:</p>
<ul>
<li><b>assert_xhtml_transitional(xhtml)</b> for asserting valid transitional XHTML</li>
<li><b>assert_xhtml_strict(xhtml)</b> for asserting valid strict XHTML</li>
<li><b>assert_schema(schema, xml)</b> for asserting that your xml validates against a schema</li>
<li><b>assert_xhtml</b> which is an alias for assert_xhtml_transitional</li>
</ul>
<p>The methods provided for RSpec are quite similar:</p>
<ul>
<li><b>be_xhtml_transitional</b> for asserting valid transitional XHTML</li>
<li><b>be_xhtml_strict</b> for asserting valid strict XHTML</li>
<li><b>be_valid_with_schema(schema)</b> for asserting that your xml validates against a schema</li>
<li><b>be_xhtml</b> which is an alias for be_xhtml_transitional</li>
</ul>
<p>MarkupValidity even works well with rails.  Here is an example rails controller test:</p>
<pre class="brush: ruby; title: ; notranslate">
require 'test_helper'
require 'markup_validity'

class AwesomeControllerTest &lt; ActionController::TestCase
  test &quot;valid markup&quot; do
    get :new
    assert_xhtml_transitional @response.body
  end
end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://tenderlovemaking.com/2009/06/12/easy-markup-validation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Nokogiri&#8217;s Slop Feature</title>
		<link>http://tenderlovemaking.com/2008/12/04/nokogiris-slop-feature/</link>
		<comments>http://tenderlovemaking.com/2008/12/04/nokogiris-slop-feature/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 17:17:49 +0000</pubDate>
		<dc:creator>Aaron Patterson</dc:creator>
				<category><![CDATA[computadora]]></category>
		<category><![CDATA[nokogiri]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://tenderlovemaking.com/?p=198</guid>
		<description><![CDATA[Oops! When I released nokogiri version 1.0.7, I totally forgot to talk about Nokogiri::Slop() feature that was added. Why is it called &#8220;slop&#8221;? It lets you sloppily explore documents. Basically, it decorates your document with method_missing() that allows you to search your document via method calls. Given this document: You may look through the tree [...]]]></description>
			<content:encoded><![CDATA[<p>Oops!  When I released <a href="http://nokogiri.rubyforge.org/">nokogiri</a> version 1.0.7, I totally forgot to talk about Nokogiri::Slop() feature that was added.  Why is it called &#8220;slop&#8221;?  It lets you sloppily explore documents.  Basically, it decorates your document with method_missing() that allows you to search your document via method calls.</p>
<p>Given this document:</p>
<pre class="brush: ruby; title: ; notranslate">
doc = Nokogiri::Slop(&lt;&lt;-eohtml)
&lt;html&gt;
  &lt;body&gt;
    &lt;p&gt;hello&lt;/p&gt;
    &lt;p class=&quot;bold&quot;&gt;bold hello&lt;/p&gt;
  &lt;body&gt;
&lt;/html&gt;
eohtml
</pre>
<p>You may look through the tree like so:</p>
<pre class="brush: ruby; title: ; notranslate">
doc.html.body.p('.bold').text # =&gt; 'bold hello'
</pre>
<p>The way this works is that method missing is implemented on every node in the document tree.  That method missing method creates an xpath or css query by using the method name and method arguments.  This means that a new search is executed for every method call.  It&#8217;s fun for playing around, but you definitely won&#8217;t get the same performance as using one specific CSS search.</p>
<p>My favorite part is that method missing is actually in the <a href="http://github.com/tenderlove/nokogiri/tree/master/lib/nokogiri/decorators/slop.rb">slop decorator</a>.  When you use the Nokogiri::Slop() method, it adds the decorator to a list that gets mixed in to every node instance at runtime using Module#extend.  That lets me have sweet method missing action, without actually putting method missing in my Node class.</p>
<p>Here is a simplified example:</p>
<pre class="brush: ruby; title: ; notranslate">
module Decorator
  def method_a
    &quot;method a&quot;
  end

  def method_b
    &quot;method b: #{super}&quot;
  end
end

class Foo
  def method_b
    &quot;inside foo&quot;
  end
end

foo = Foo.new
foo.extend(Decorator)

puts foo.method_a # =&gt; 'method a'
puts foo.method_b # =&gt; 'method b: inside foo'

foo2 = Foo.new
puts foo2.method_b # =&gt; 'inside foo'
puts foo2.method_a # =&gt; NoMethodError
</pre>
<p>Module#extend is used to add functionality to the <strong>instance</strong> &#8216;foo&#8217;, but not &#8216;foo2&#8242;.  Both &#8216;foo&#8217; and &#8216;foo2&#8242; are instances of Foo, but using Module#extend, we can conditionally add functionality <strong>without monkey patching</strong> and keeping a clean separation of concerns.  You can even reach previous functionality by calling super.</p>
<p>But wait!  There&#8217;s more!  You can stack up these decorators as much as you want.  For example:</p>
<pre class="brush: ruby; title: ; notranslate">
module AddAString
  def method
    &quot;Added a string: #{super}&quot;
  end
end

module UpperCaseResults
  def method
    super.upcase
  end
end

class Foo
  def method
    &quot;foo&quot;
  end
end

foo = Foo.new
foo.extend(AddAString)
foo.extend(UpperCaseResults)

puts foo.method # =&gt; 'ADDED A STRING: FOO'
</pre>
<p>Conditional functionality added to methods with no weird &#8220;alias method chain&#8221; involvement.  Awesome!</p>
<p>I love ruby!</p>
]]></content:encoded>
			<wfw:commentRss>http://tenderlovemaking.com/2008/12/04/nokogiris-slop-feature/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Write your Rails view in&#8230;&#8230;.  JavaScript?</title>
		<link>http://tenderlovemaking.com/2008/05/06/write-your-rails-view-in-javascript/</link>
		<comments>http://tenderlovemaking.com/2008/05/06/write-your-rails-view-in-javascript/#comments</comments>
		<pubDate>Tue, 06 May 2008 18:33:30 +0000</pubDate>
		<dc:creator>Aaron Patterson</dc:creator>
				<category><![CDATA[johnson]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://tenderlovemaking.com/?p=139</guid>
		<description><![CDATA[In my last post about Johnson, I said that next time I would talk about the JavaScript parse tree that Johnson provides. Well, I changed my mind. Sorry. I want to write about a rails plugin that I added to Johnson. Brohuda Katz wrote an ERb type parser in JavaScript, and added it to the [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="/2008/04/23/take-it-to-the-limit-one-more-time/">last post about Johnson</a>, I said that next time I would talk about the JavaScript parse tree that <a href="http://github.com/jbarnette/johnson/tree/master">Johnson</a> provides.  Well, I changed my mind.  Sorry.</p>
<p>I want to write about a rails plugin that I added to Johnson.  <a href="http://www.yehudakatz.com/">Brohuda Katz</a> wrote an <a href="http://github.com/jbarnette/johnson/tree/master/js/johnson/template.js">ERb type parser in JavaScript</a>, and added it to the (yet to be released) Johnson distribution.  With that in mind, and looking at the new template handlers in edge rails, I was able to throw together a rails plugin that allows me to use JavaScript in my rails view code.</p>
<p>Lets get to the code.  Here is my controller:</p>
<pre class="brush: ruby; title: ; notranslate">
class JohnsonController &lt; ApplicationController
  def index
    @users = User.find(:all)
  end
end
</pre>
<p>And my EJS view (the file is named index.html.ejs):</p>
<pre class="brush: php; title: ; notranslate">
&lt;% for(var user in at.users) { %&gt;
  &lt;%= user.first_name() %&gt;&lt;br /&gt;
&lt;% } %&gt;
</pre>
<p>The johnson rails plugin puts controller instance variables in to a special javascript variable called &#8220;at&#8221;.  The &#8220;at&#8221; variable is actually a proxy to the controller, lazily fetching instance variables from the controller and importing those objects in to javascript land.</p>
<p>Lets take a look at the plugin, its only a few lines:</p>
<pre class="brush: ruby; title: ; notranslate">
class EJSHandler &lt; ActionView::TemplateHandler
  class EJSProxy # :nodoc:
    def initialize(controller)
      @controller = controller
    end

    def key?(pooperty)
      @controller.instance_variables.include?(&quot;@#{pooperty}&quot;)
    end

    def [](pooperty)
      @controller.instance_variable_get(&quot;@#{pooperty}&quot;)
    end

    def []=(pooperty, value)
      @controller.instance_variable_set(&quot;@#{pooperty}&quot;, value)
    end
  end

  def initialize(view)
    @view = view
  end

  def render(template)
    ctx = Johnson::Context.new
    ctx.evaluate('Johnson.require(&quot;johnson/template&quot;);')
    ctx['template'] = template.source
    ctx['controller'] = @view.controller
    ctx['at'] = EJSProxy.new(@view.controller)

    ctx.evaluate('Johnson.templatize(template).call(at)')
  end
end

ActionView::Template.register_template_handler(&quot;ejs&quot;, EJSHandler)
</pre>
<p>When the template gets rendered (the render method), I wrap the controller with an EJS proxy, then compile the template into a javascript function, and call that function.  The &#8220;at&#8221; variable is set to the EJSProxy before executing the template, and all property accessing on the &#8220;at&#8221; variable is passed along to fetching instance variables from the controller.</p>
<p>Server side javascript coding in rails.  Weird, eh?</p>
]]></content:encoded>
			<wfw:commentRss>http://tenderlovemaking.com/2008/05/06/write-your-rails-view-in-javascript/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Profiling Database Queries in Rails</title>
		<link>http://tenderlovemaking.com/2008/03/13/profiling-database-queries-in-rails/</link>
		<comments>http://tenderlovemaking.com/2008/03/13/profiling-database-queries-in-rails/#comments</comments>
		<pubDate>Thu, 13 Mar 2008 21:16:37 +0000</pubDate>
		<dc:creator>Aaron Patterson</dc:creator>
				<category><![CDATA[computadora]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://tenderlovemaking.com/2008/03/13/profiling-database-queries-in-rails/</guid>
		<description><![CDATA[Despite the recent Ruby webserver speed contests, most of the slowness at my job results from slow (or too many) database queries. To help keep database queries down, I added a stats to every page that shows the number of queries vs. cache hits, the number of rows returned, and the amount of data transferred [...]]]></description>
			<content:encoded><![CDATA[<p>Despite the recent Ruby webserver <a href="http://www.rubyinside.com/ebb-web-framework-http-server-786.html">speed contests</a>, most of the slowness at <a href="http://adready.com/">my job</a> results from slow (or too many) database queries.</p>
<p>To help keep database queries down, I added a stats to every page that shows the number of queries vs. cache hits, the number of rows returned, and the amount of data transferred from the database.  In this screenshot I&#8217;m using the &#8220;live&#8221; environment, 3 cache hits, 169 misses, 577 rows returned, and 458.9k data transferred.  Clicking the box hides it, and clicking &#8220;Super Hide!&#8221; hides the box and sets a cookie so that the box doesn&#8217;t show up again for a while.</p>
<p><a href="http://www.flickr.com/photos/aaronp/2331927606/" title="Debug Window by fakebeard, on Flickr"><img src="http://farm3.static.flickr.com/2106/2331927606_46cc9fa937.jpg" width="500" height="187" alt="Debug Window" /></a></p>
<p>To get this working, first I monkey patch the MysqlAdapter to collect database stats:</p>
<pre class="brush: ruby; title: ; notranslate">
  ActiveRecord::ConnectionAdapters::MysqlAdapter.module_eval do
    @@stats_queries = @@stats_bytes = @@stats_rows = 0

    def self.get_stats
      { :queries =&gt; @@stats_queries,
        :rows =&gt; @@stats_rows,
        :bytes =&gt; @@stats_bytes }
    end
    def self.reset_stats
      @@stats_queries = @@stats_bytes = @@stats_rows = 0
    end

    def select_with_stats(sql, name)
      bytes = 0
      rows = select_without_stats(sql, name)
      rows.each do |row|
        row.each do |key, value|
          bytes += key.length
          bytes += value.length if value
        end
      end
      @@stats_queries += 1
      @@stats_rows += rows.length
      @@stats_bytes += bytes
      rows
    end
    alias_method_chain :select, :stats
  end
</pre>
<p>Next I patched the QueryCache to keep track of hits and misses:</p>
<pre class="brush: ruby; title: ; notranslate">
  ActiveRecord::ConnectionAdapters::QueryCache.module_eval do
    @@hits = @@misses = 0

    def self.get_stats
      { :hits =&gt; @@hits,
        :misses =&gt; @@misses }
    end
    def self.reset_stats
      @@hits = @@misses = 0
    end

    def cache_sql_with_stats(sql, &amp;block)
      if @query_cache.has_key?(sql)
        @@hits += 1
      else
        @@misses += 1
      end
      cache_sql_without_stats(sql, &amp;block)
    end
    alias_method_chain :cache_sql, :stats
  end
</pre>
<p>Then modify ActionController to reset stats for each request:</p>
<pre class="brush: ruby; title: ; notranslate">
  ActionController::Base.module_eval do
    def perform_action_with_reset
      ActiveRecord::ConnectionAdapters::MysqlAdapter::reset_stats
      ActiveRecord::ConnectionAdapters::QueryCache::reset_stats
      perform_action_without_reset
    end

    alias_method_chain :perform_action, :reset

    def active_record_runtime(runtime)
      stats = ActiveRecord::ConnectionAdapters::MysqlAdapter::get_stats
      &quot;#{super} #{sprintf(&quot;%.1fk&quot;, stats[:bytes].to_f / 1024)} queries: #{stats[:queries]}&quot;
    end
  end
</pre>
<p>Just drop all that inside the after_initialize in your development.rb and you&#8217;ll get the nice stats.  After that, just create a partial that displays the stats and include the partial at the bottom of your layout.  Our partial looks like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;% unless %w(production test).include?(RAILS_ENV) -%&gt;
  &lt;h4 id=&quot;debug&quot; onclick=&quot;$(this).remove()&quot; style=&quot;background:pink;text-align:center;position:absolute;top:16px;left:35%;padding:0.5em;border: 2px solid red;&quot;&gt;
  &lt;%= RAILS_ENV %&gt;
  &lt;br /&gt;
  &lt;% if ActiveRecord::ConnectionAdapters::QueryCache.respond_to?(:get_stats) %&gt;
    &lt;% stats = ActiveRecord::ConnectionAdapters::QueryCache.get_stats %&gt;
    Queries: &lt;%= stats[:hits] %&gt; / &lt;%= stats[:misses] %&gt; /
    &lt;%= number_to_percentage((stats[:hits].to_f / (stats[:hits] + stats[:misses])) * 100, :precision =&gt; 0) %&gt;
    |
  &lt;% end %&gt;
  &lt;% if ActiveRecord::ConnectionAdapters::MysqlAdapter.respond_to?(:get_stats) %&gt;
    &lt;% stats = ActiveRecord::ConnectionAdapters::MysqlAdapter.get_stats %&gt;
    Rows: &lt;%= stats[:rows] %&gt; |
    Transfer: &lt;%= sprintf(&quot;%.1fk&quot;, stats[:bytes].to_f / 1024) %&gt;
  &lt;% end %&gt;
  &lt;p style=&quot;margin:0&quot;&gt;
    &lt;a style=&quot;color:magenta&quot; href=&quot;#&quot; onclick=&quot;superHide()&quot;&gt;super hide!&lt;/a&gt;
  &lt;/p&gt;
  &lt;/h4&gt;
  &lt;script type=&quot;text/javascript&quot;&gt;
    function superHide() {
      document.cookie = 'debug=hidden; path=/; domain=&lt;%= request.host %&gt;; max-age=14400';
    }
    if(document.cookie.indexOf('debug=hidden') != -1) {
      $('debug').hide();
    }
  &lt;/script&gt;
&lt;% end -%&gt;
</pre>
<p>It&#8217;s a little work, but it helps keep my mind on reducing the queries.  With enough work, one of these days the speed of the webserver will matter to me.  Thanks to <a href="http://gurge.com/blog/2006/11/09/rails-sql-logging-improvements/">Adam Doppelt</a> for the basis of this monkey patch.  Any bugs are mine, not his!</p>
]]></content:encoded>
			<wfw:commentRss>http://tenderlovemaking.com/2008/03/13/profiling-database-queries-in-rails/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Trigger Happy</title>
		<link>http://tenderlovemaking.com/2007/03/01/trigger-happy/</link>
		<comments>http://tenderlovemaking.com/2007/03/01/trigger-happy/#comments</comments>
		<pubDate>Thu, 01 Mar 2007 21:32:27 +0000</pubDate>
		<dc:creator>Aaron Patterson</dc:creator>
				<category><![CDATA[computadora]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://tenderlovemaking.com/2007/03/01/trigger-happy/</guid>
		<description><![CDATA[I&#8217;ve just released &#8220;Trigger Happy&#8220;, a rails plugin that adds support for triggers in your Active Record Migrations. To install the plugin just do this: script/plugin install svn://rubyforge.org/var/svn/artriggers/trunk/trigger_happy [/sourcecode] To add a trigger do this: To drop a trigger do this: It only supports mysql for now, but I plan on having other database supported [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just released &#8220;<a href="http://artriggers.rubyforge.org/">Trigger Happy</a>&#8220;, a rails plugin that adds support for triggers in your Active Record Migrations.  To install the plugin just do this:</p>
<p><code><br />
script/plugin install svn://rubyforge.org/var/svn/artriggers/trunk/trigger_happy<br />
[/sourcecode]</p>
<p>To add a trigger do this:</p>
<pre class="brush: ruby; title: ; notranslate">
add_trigger &quot;ai_people&quot;,
  <img src='http://tenderlovemaking.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> n         =&gt; 'people',
  :timing     =&gt; 'after',
  :event      =&gt; 'insert',
  :statement  =&gt; 'INSERT INTO log (id, timestamp) VALUES (NEW.id, NOW())'
</pre>
<p>To drop a trigger do this:</p>
<pre class="brush: ruby; title: ; notranslate">
drop_trigger &quot;ai_people&quot;
</pre>
<p>It only supports mysql for now, but I plan on having other database supported in the future.</p>
]]></content:encoded>
			<wfw:commentRss>http://tenderlovemaking.com/2007/03/01/trigger-happy/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Audit Logs with ActiveRecord</title>
		<link>http://tenderlovemaking.com/2007/03/01/audit-logs-with-activerecord/</link>
		<comments>http://tenderlovemaking.com/2007/03/01/audit-logs-with-activerecord/#comments</comments>
		<pubDate>Thu, 01 Mar 2007 18:02:19 +0000</pubDate>
		<dc:creator>Aaron Patterson</dc:creator>
				<category><![CDATA[computadora]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://tenderlovemaking.com/2007/03/01/audit-logs-with-activerecord/</guid>
		<description><![CDATA[I&#8217;ve been trying to create an audit log for a few (12) tables, and unfortunately ActiveRecord seems to be falling flat for what I want to do. First I&#8217;ll describe whats out there already to do this, then I&#8217;ll talk about what I had to do. There are a couple nice plugins out there for [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been trying to create an audit log for a few (12) tables, and unfortunately ActiveRecord seems to be falling flat for what I want to do.  First I&#8217;ll describe whats out there already to do this, then I&#8217;ll talk about what I had to do.</p>
<p>There are a couple nice plugins out there for helping you keep track of changes to your records.  The first one is <a href="http://ar-versioned.rubyforge.org/">acts_as_versioned</a>.  acts_as_versioned will copy your record to a version table whenever there is an insert or update, then increase a version number in the original table.  It also automatically adds a list of versions to your original model, and lets you revert to any particular version.  This is great, and almost exactly what I needed.  I didn&#8217;t really need the ability to revert to a version, but that just seemed like gravy on top.  The only problem with acts_as_versioned comes in when you try to keep track of changes to habtm relationships.  But this is where the second plugin comes in to play.</p>
<p>The second plugin is called <a href="http://svn.livsey.org/plugins/acts_as_versioned_association/">acts_as_versioned_association</a>.  This plugin will help you keep track of changes to your relationships.  acts_as_versioned_association is built on top of acts_as_versioned.  They way it works is by setting the owner model to acts_as_versioned, then when any associations are updated, it writes a new version of the owner model, then writes the associations to a associations version table.  So if you were to have an Article model that has and belongs to many Documents, you would need 5 tables to represent that:</p>
<ol>
<li>articles</li>
<li>articles_versions</li>
<li>documents</li>
<li>articles_documents</li>
<li>articles_documents_versions</li>
</ol>
<p>If the association changes, a record is written to articles (to increase the version number), articles_versions, articles_documents, and articles_documents_versions.  But what happens if Article has 10 versioned habtm relationships, and just one of those relationships changes?  Then a record will get written to every habtm version table for just one change.  Thats 12 writes for a change to just one relationship.  That will not scale&#8230;.</p>
<p>Fortunately I don&#8217;t care about reverting to a previous version.  All I care about is what changed, and when.  So my favorite solution for this problem is to add triggers to the tables that may change.  That way I only get one extra write when a relationship changes.  Just copy the row to another table with a timestamp and an action.</p>
<p><strong>But what about has_many :through?</strong></p>
<p>has_many :through allows you to put a model on top of the join table.  Then I could just drop acts_as_versioned on top of that model and be done.  I would have used this solution except that I ran in to a bug.  has_many :through does not support all of the same array manipulation that habtm does.  For example, you can append (<<) to has_many :through and habtm, but the <em>clear</em> method does not work the same way on has_many :through.  Also, has_many :through does not set an <em>attribute=</em> method like habtm does.</p>
]]></content:encoded>
			<wfw:commentRss>http://tenderlovemaking.com/2007/03/01/audit-logs-with-activerecord/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

