<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <title>Hotlit - Home</title>
  <id>tag:blog.wesgibbs.org,2008:mephisto/</id>
  <generator uri="http://mephistoblog.com" version="0.7.3">Mephisto Noh-Varr</generator>
  <link href="http://blog.wesgibbs.org/feed/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="http://blog.wesgibbs.org/" rel="alternate" type="text/html"/>
  <updated>2008-08-12T23:36:49Z</updated>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-08-12:27</id>
    <published>2008-08-12T23:36:00Z</published>
    <updated>2008-08-12T23:36:49Z</updated>
    <link href="http://blog.wesgibbs.org/2008/8/12/google-analytics" rel="alternate" type="text/html"/>
    <title>Google Analytics and a subdomain-per-account site</title>
<content type="html">
            &lt;p&gt;MadPolitic has a collection of about a half dozen or so static pages that I refer to as the public site. These are all served off the www.madpolitic.com domain (i.e. http://www.madpolitic.com/faq and http://www.madpolitic.com/pricing). The dynamic portions of the app are all served through subdomain-per-account domains (like http://savethewhales.madpolitic.com/ and http://nowalmart.madpolitic.com/petition).&lt;/p&gt;


	&lt;p&gt;Setting up Google Analytics for the public portion of the site was straightforward. All of my static content is served through the same layout, so all I had to do was include the GA javascript code in that layout to begin tracking.&lt;/p&gt;


	&lt;p&gt;For the most part, I&#8217;m not interested in tracking traffic through my user&#8217;s sites at their individual subdomains. However, there is one case where this is necessary: tracking new user sign-ups as a goal conversion.&lt;/p&gt;


	&lt;p&gt;When a user signs up at MadPolitic, they are redirected from the sign up form at http://www.madpolitic.com/signup to the home page of their new MadPolitic site at http://sitename.madpoltic.com. That landing page is not part of the static content that is tracked by adding the GA code to my common layout. I could add the tracking code to this page, but then it would be counting every visit to that page and I&#8217;m not interested in every visit. I&#8217;m only interested in the first one which signifies that a new user has signed up.&lt;/p&gt;


	&lt;p&gt;To further complicate things, it is served by a different subdomain than all the static pages. I learned that this is significant when setting up your GA profile.&lt;/p&gt;


	&lt;h2&gt;If you&#8217;ll be tracking across different subdomains&lt;/h2&gt;


	&lt;p&gt;The trick here is to make sure your GA profile is set up for your primary domain, in my case: madpolitic.com as opposed to www.madpolitic.com. Using [domain].[tld] as opposed to [subdomain].[domain].[tld] gives you the flexibility to track page visits across multiple subdomains within the same GA profile. If you set the primary domain to [subdomain].[domain].[tld], you lose that option.&lt;/p&gt;


	&lt;h2&gt;Tracking dynamically generated pages with the same &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; path&lt;/h2&gt;


	&lt;p&gt;In my case, I wanted to track http://www.madpolitic.com separately from http://usersite.madpolitic.com. To GA, both of these are the same Exact Match: /index.html. I cannot use the Head Match option because I do not know what the user subdomain &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; will be ahead of time. I needed a way to tell GA that http://usersite.madpolitic.com/index.html was different than http://www.madpolitic.com/index.html.&lt;/p&gt;


	&lt;p&gt;To do this, I set up a GA goal for an Exact Match on &#8221;/new_user.html&#8221;. In the code that generates the index.html page for the user&#8217;s site, I added the GA code again, but this time I gave &lt;code&gt;_trackPageview()&lt;/code&gt; an argument.&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;pageTracker._trackPageview(&amp;quot;/new_user.html&amp;quot;);&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The string isn&#8217;t important, as long as it matches the Goal you&#8217;ve set up in GA.&lt;/p&gt;


	&lt;p&gt;I used a token that is placed in the request the first time the page is rendered but never again to make sure I only counted the goal the one time.&lt;/p&gt;


	&lt;h2&gt;Partializing and Production&lt;/h2&gt;


	&lt;p&gt;A this point, I&#8217;m using the GA code in three different places in my app. Because of this, I moved the code out into a _google_analytics.html.erb partial and made the parameter that is passed to _trackPageview dynamic. I also wrapped the whole thing in a condition that ensure the script is only rendered if the app is in production so page views while in development mode are not counted.&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;&amp;lt;% if RAILS_ENV == 'production' %&amp;gt;
  &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
    var gaJsHost = ((&amp;quot;https:&amp;quot; == document.location.protocol) ? &amp;quot;https://ssl.&amp;quot; : &amp;quot;http://www.&amp;quot;);
    document.write(unescape(&amp;quot;%3Cscript src='&amp;quot; + gaJsHost + &amp;quot;google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E&amp;quot;));
  &amp;lt;/script&amp;gt;
  &amp;lt;script type=&amp;quot;text/javascript&amp;quot;&amp;gt;
    var pageTracker = _gat._getTracker(&amp;quot;UA-0000000-0&amp;quot;);
    pageTracker._trackPageview(&amp;lt;%= defined?(pageview_argument) ? &amp;quot;\&amp;quot;#{pageview_argument}\&amp;quot;&amp;quot; : '' %&amp;gt;);
  &amp;lt;/script&amp;gt;
&amp;lt;% end %&amp;gt;&lt;/code&gt;&lt;/pre&gt;
          </content>  </entry>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-05-12:3</id>
    <published>2008-05-12T02:08:00Z</published>
    <updated>2008-05-12T02:13:41Z</updated>
    <link href="http://blog.wesgibbs.org/2008/5/12/domain-mapping" rel="alternate" type="text/html"/>
    <title>Domain Mapping</title>
<content type="html">
            &lt;p&gt;I built &lt;a href=&quot;http://www.madpolitic.com&quot;&gt;MadPolitic&lt;/a&gt; to be an account-per-subdomain site. So when a user signs up for an account, they can choose a site name that gets prepended to the domain, e.g. &lt;code&gt;mysite.madpolitic.com&lt;/code&gt;. Frequently, MadPolitic&#8217;s users will have registered their own domain name and want to map it to their MadPolitic site. MadPolitic is a publishing system for people or groups with a cause, so they might have domains like &lt;code&gt;savethefarmersmarket.com&lt;/code&gt; or &lt;code&gt;stopeatingthewhales.com&lt;/code&gt;. How do you map a domain name to a specific user site in your Rails app? Here&#8217;s how I did it.&lt;/p&gt;


	&lt;h2&gt;Part I: Some Assembly Required&lt;/h2&gt;


	&lt;p&gt;First of all, it&#8217;s worth noting that there is no way to fully automate this process. The user has to purchase their domain outside of your application through the registrar of their choice. They also have to use that registrar&#8217;s administration console to make some &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; configuration changes. Since I can&#8217;t do any of those things for them, I instead provide my users with detailed &lt;a href=&quot;http://www.madpolitic.com/faq#hq8&quot;&gt;instructions&lt;/a&gt; on making the &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; changes for each of the more popular registrars. This is a bit of a hassle since these sites are beyond my control and can and do frequently tweak their menus or UI enough to render my instructions incorrect.&lt;/p&gt;


	&lt;h5&gt;Buy a Domain&lt;/h5&gt;


	&lt;p&gt;Let&#8217;s say we have a photosensitive user named Linda who is outraged at the city for installing street lights in her neighborhood. She created her community activism site at &lt;code&gt;lindasmad.madpolitic.com&lt;/code&gt; but would rather people could find her at a more user-friendly &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; like &lt;code&gt;www.darkenmystreet.com&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Linda is also a big Danica Patrick fan, so she heads to GoDaddy and registers her new domain.&lt;/p&gt;


	&lt;h5&gt;Configure &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt;: the A record&lt;/h5&gt;


	&lt;p&gt;To map &lt;code&gt;darkenmystreet.com&lt;/code&gt; and &lt;code&gt;www.darkenmystreet.com&lt;/code&gt; to her MadPolitic site, Linda has to make changes to some &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; records on her registrar&#8217;s name servers. A newly registered domain is typically set to use a pair of name servers under the control of the registrar. Most of the more popular registrars offer some version of a &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; control panel that lets users modify the &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; settings for their domain on those name servers. In the GoDaddy administration console, for instance, that feature is called &lt;em&gt;Total &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; Control and MX Records&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;First, she has to edit what is called an A record, also called an address record. The sole purpose of an address record is to map a domain name to an IP address. This is the function that most of us think of when we think of &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; servers. They translate domain names to IP addresses. When you register a new domain, an A record is typically created that points your domain to one of the registrars IP addresses.&lt;/p&gt;


	&lt;p&gt;Linda edits the A record and sets &#8216;Host&#8217; to &#8216;darkenmystreet.com&#8217; and &#8216;Points to&#8217; to &#8216;72.249.74.216&#8217;, which is the MadPolitic IP address. In most &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; servers there is a shorthand for referring to the current domain: the &#8216;at&#8217; sign (&lt;code&gt;@&lt;/code&gt;). So for &#8216;Host&#8217;, Linda could also enter &lt;code&gt;@&lt;/code&gt;.&lt;/p&gt;


	&lt;h5&gt;Configure &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt;: the &lt;span class=&quot;caps&quot;&gt;CNAME&lt;/span&gt; record&lt;/h5&gt;


	&lt;p&gt;Linda has one more change to make to the &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; records. She also wants to be sure that someone entering &lt;code&gt;www.darkenmystreet.com&lt;/code&gt; winds up at her MadPolitic site. To do this, she needs to create a &lt;span class=&quot;caps&quot;&gt;CNAME&lt;/span&gt; record, also called an alias. This record has two primary pieces of information: the alias name and the host it points to. Linda enters &lt;code&gt;www&lt;/code&gt; for the alias name and &lt;code&gt;@&lt;/code&gt; for the &#8216;points to&#8217; field. Sometimes this record is automatically created by the registrar and so nothing needs to be done.&lt;/p&gt;


	&lt;p&gt;Once all the &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; information for her new domain propagates out through the Internet, both &lt;code&gt;darkenmystreet.com&lt;/code&gt; and &lt;code&gt;www.darkenmystreet.com&lt;/code&gt; will resolve to the MadPolitic IP address.&lt;/p&gt;


	&lt;h5&gt;Tell MadPolitic about the new domain&lt;/h5&gt;


	&lt;p&gt;The final step for Linda is to log into her MadPolitic account and register her new domain name with my Rails app. I&#8217;ll use this to map requests coming from the &lt;code&gt;darkenmystreet.com&lt;/code&gt; host to Linda&#8217;s MadPolitic site.&lt;/p&gt;


	&lt;h2&gt;Part II: About That Rails App&lt;/h2&gt;


	&lt;p&gt;That takes care of the first half of the equation: requests for the mapped domain are getting routed to my server. At this point, everything else is under my control. I have an apache virtual host set up to catch requests for port 80 from any host and proxy them to my Rails app. In the app, I have a before_filter in &lt;code&gt;ApplicationController&lt;/code&gt; called &lt;code&gt;set_site&lt;/code&gt; with this logic&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;...
if request.host.ends_with? 'madpolitic.com'
  # the request is for a site on the madpolitic domain with no domain mapping
  sitename = request.subdomains(tld_length = 1)[0]
  session[:site] = Site.find_by_sitename(sitename).id
else
  # the host is not *.madpolitic.com so see if the host maps to a madpolitic site
  # I actually cache a mapping of mapped_domain =&amp;gt; sitename so I don' t hit the db each time; removed for this example
  session[:site] = Site.find_by_mapped_domain(request.host)
end
if !session[:site]
  logger.error &amp;quot;[#{Time.now.utc.strftime('%m-%d-%Y %H%:%M:%S')}]: Failed to locate site based on host of #{request.host}.&amp;quot;
  redirect_to 'http://www.madpolitic.com/500.html', :status =&amp;gt; 500
  return false
end
...&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;This method checks &lt;code&gt;request.host&lt;/code&gt; to see if it ends in &lt;code&gt;.madpolitic.com&lt;/code&gt; and handles it like a typical subdomain-based request and serves up the correct site accordingly. If the host does not end in &lt;code&gt;.madpolitic.com&lt;/code&gt; then it might be a mapped domain and I try pulling a site from the database using the mapped domain.&lt;/p&gt;


	&lt;p&gt;Since Linda registered her mapped domain with my Rails app, the find is successful. If the find fails, then it&#8217;s possible someone followed all the directions, but failed to go to the MadPolitic administration console and enter the mapped domain. When I don&#8217;t find a site, I can serve an oops page and offer some helpful troubleshooting suggestions.&lt;/p&gt;


	&lt;h2&gt;Epilogue: Follow That Request&lt;/h2&gt;


	&lt;p&gt;Now let&#8217;s meet Robert. He lives on Linda&#8217;s street and has been infatuated with her for months. When he heard about her campaign to have the street lights removed, he became an impassioned supporter of her cause. He gets the &lt;span class=&quot;caps&quot;&gt;URL&lt;/span&gt; from a flyer in the local coffee shop and logs on to sign the petition.&lt;/p&gt;


When Robert enters http://www.darkenmystreet.com into his browser and hits enter, here&#8217;s what happens (assuming he&#8217;s never hit that domain before). 
	&lt;ol&gt;
	&lt;li&gt;His browser sends a request out to one of the &lt;span class=&quot;caps&quot;&gt;DNS&lt;/span&gt; servers of Robert&#8217;s &lt;span class=&quot;caps&quot;&gt;ISP&lt;/span&gt;. &lt;/li&gt;
		&lt;li&gt;That server (called the Resolver in this scheme) has never had a request for &lt;code&gt;www.darkenmystreet.com&lt;/code&gt; before, so it doesn&#8217;t know the IP. It passes the request on to one of the 13 root name servers. &lt;/li&gt;
		&lt;li&gt;That server replies to the Resolver saying &#8220;I don&#8217;t know about that domain, but this root name server should.&#8221; &lt;/li&gt;
		&lt;li&gt;The Resolver then contacts that root name server with the request. That root server has a record mapping the domain to a name server and returns the address of that name server to the Resolver. &lt;/li&gt;
		&lt;li&gt;Now the Resolver contacts that name server. This is the name server run by GoDaddy that Linda configured when she set the A record and &lt;span class=&quot;caps&quot;&gt;CNAME&lt;/span&gt; record. &lt;/li&gt;
		&lt;li&gt;Those record entries translate &lt;code&gt;www.darkenmystreet.com&lt;/code&gt; to the MadPolitic IP address and return it to the Resolver. &lt;/li&gt;
		&lt;li&gt;The Resolver caches the information for future requests and returns the IP to the browser. &lt;/li&gt;
		&lt;li&gt;The browser sends its request directly to the MadPolitic IP.&lt;/li&gt;
		&lt;li&gt;My Apache server is listening on that IP on port 80, and intercepts the request. The host in the request header matches up with a virtual server I have configured and Apache proxies the request on to Mongrel and my Rails app.&lt;/li&gt;
		&lt;li&gt;Rails serves up the page Robert was looking for.&lt;/li&gt;
		&lt;li&gt;Robert comments on one of Linda&#8217;s blog postings with an awkwardly-worded poem wherein he likens his love for Linda to a streetlight.&lt;/li&gt;
	&lt;/ol&gt;
          </content>  </entry>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-05-02:11</id>
    <published>2008-05-02T00:13:00Z</published>
    <updated>2008-05-02T00:14:25Z</updated>
    <link href="http://blog.wesgibbs.org/2008/5/2/transactional-fixtures" rel="alternate" type="text/html"/>
    <title>!transactional fixtures</title>
<content type="html">
            &lt;p&gt;I am referring to transactional fixtures, and I had a mistaken understanding of how they worked. For my own notes, here&#8217;s what I learned.&lt;/p&gt;


	&lt;p&gt;By default, TestCase and RSpec use transactional fixtures. This is set in the respective helper file (&lt;code&gt;test/test_helper.rb&lt;/code&gt; or &lt;code&gt;spec/spec_helper.rb&lt;/code&gt;). Transactional fixtures is a terrible name for this feature, because the fixtures are not transactional. What transactional fixtures actually means is that each test method is executed in a database transaction which is rolled back when the test is finished.&lt;/p&gt;


	&lt;p&gt;Here&#8217;s what happens when you have a test class with several test methods and one fixture (let&#8217;s say &lt;code&gt;:users&lt;/code&gt;) specified&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;all rows are deleted from the users table&lt;/li&gt;
		&lt;li&gt;an insert is executed for each user listed in the &lt;code&gt;:users&lt;/code&gt; fixture&lt;/li&gt;
		&lt;li&gt;for each test method in the test case
	&lt;ul&gt;
	&lt;li&gt;a transaction is started&lt;/li&gt;
		&lt;li&gt;the test is run&lt;/li&gt;
		&lt;li&gt;the transaction is rolled back&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;This means that when the class is finished executing, all the fixture data that was loaded is left in the database.&lt;/p&gt;


	&lt;p&gt;There&#8217;s a gotcha lurking here, which is what bit me. Let&#8217;s say you have two models as follows&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class User &amp;lt; ActiveRecord::Base
  has_many :articles
end

class Zebra &amp;lt; ActiveRecord::Base
  belongs_to :user
end

class UserTest &amp;lt; Test::Unit::TestCase
  fixtures :users
  # test methods here
end

class ZebraTest &amp;lt; Test::Unit::TestCase
  fixtures :zebras
  # test methods here
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;When you run &lt;code&gt;rake test:models&lt;/code&gt;, all your zebra tests pass. However, if you &lt;code&gt;rake db:test:prepare&lt;/code&gt; and run &lt;code&gt;ruby test/unit/zebra_test.rb&lt;/code&gt;, suddenly tests are failing. This is because when you run the entire suite, the User test case is running first and its fixture, &lt;code&gt;:users&lt;/code&gt;, is getting loaded into the database. When the suite gets to the Zebra test case, the test methods that rely on rows in the users table find the data that was left over from the User test case and so they work. However, when you run the Zebra test case in isolation on a fresh test database, that user data is not loaded, so the tests fail.&lt;/p&gt;


	&lt;p&gt;This has led to a new best practice for me when writing tests. I always make sure I&#8217;m running the TestCase against a clean database while I&#8217;m writing it. I do this by frequently running &lt;code&gt;rake db:test:prepare&lt;/code&gt;. That way I know that the TestCase has the fixture data it needs to run on its own and is not dependent on data that might be left over from the fixtuers of other tests.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-04-19:10</id>
    <published>2008-04-19T15:17:00Z</published>
    <updated>2008-07-15T17:53:57Z</updated>
    <link href="http://blog.wesgibbs.org/2008/4/19/counter-cache" rel="alternate" type="text/html"/>
    <title>:counter_cache no workie</title>
<content type="html">
            &lt;p&gt;I ran into a gotcha trying to use the &lt;code&gt;:counter_cache&lt;/code&gt; option on a &lt;code&gt;belongs_to&lt;/code&gt; association today. In short, the &lt;code&gt;:counter_cache&lt;/code&gt; option can be used on the &lt;code&gt;belongs_to&lt;/code&gt; end of a one-to-many association to improve the performance of querying the size of the association. As a quick example&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Dog &amp;lt; ActiveRecord::Base
  has_many :fleas
end

class Flea &amp;lt; ActiveRecord::Base
  belongs_to :dog
end

charlie = Dog.create(:name =&amp;gt; &amp;quot;charlie&amp;quot;)
charlie.fleas.create(:name =&amp;gt; &amp;quot;fleabert&amp;quot;)
charlie.reload
charlie.fleas.size&lt;/code&gt;&lt;/pre&gt;

When this code is run from &lt;code&gt;script/console&lt;/code&gt;, the development log will show you that in order to get the size of the fleas association on charlie, this sql was run
&lt;pre&gt;
SELECT count(*) AS count_all FROM `fleas` WHERE (fleas.dog_id = 1)
&lt;/pre&gt;

	&lt;p&gt;If you use &lt;code&gt;:counter_cache&lt;/code&gt;, however, you can save yourself that extra db query when trying to determine the size of an association.&lt;/p&gt;


	&lt;p&gt;The Rails Framework docs explain the usage of the option, and in its simple form, all you need to do is add &lt;code&gt;:counter_cache =&amp;gt; true&lt;/code&gt; to the &lt;code&gt;belongs_to&lt;/code&gt; association. So in the above example,&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Flea &amp;lt; ActiveRecord::Base
  belongs_to :dog, :counter_cache =&amp;gt; true
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;and add a column named &lt;code&gt;#{table_name}_count&lt;/code&gt; to the associate class (so add fleas_count to dog, in this case) of type integer.&lt;/p&gt;


	&lt;p&gt;I did this and then reran the code where I create a dog and an associated flea, reload the dog, then ask for the size of the flea association. My development log was still showing a &lt;code&gt;SELECT count(*)&lt;/code&gt; statement being executed.&lt;/p&gt;


I studied the log a bit more and found how ActiveRecord was trying to manage the counter cache. After creating the flea and adding it to the fleas association, this query is run
&lt;pre&gt;
UPDATE dogs SET `fleas_count` = `fleas_count` + 1 WHERE (`id` = 1)
&lt;/pre&gt;

	&lt;p&gt;I checked the structure of the dogs table, and noticed that the default value for the &lt;code&gt;fleas_count&lt;/code&gt; count column was &lt;code&gt;NULL&lt;/code&gt;. Obviously trying to add 1 to &lt;span class=&quot;caps&quot;&gt;NULL&lt;/span&gt; wasn&#8217;t going to be successful.&lt;/p&gt;


The answer, obviously, was to update my migration and specify a default value of 0 for the counter_cache column
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;t.integer :fleas_count, :default =&amp;gt; 0&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The counter cache then worked as advertised.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-04-17:9</id>
    <published>2008-04-17T02:04:00Z</published>
    <updated>2008-04-17T02:05:09Z</updated>
    <link href="http://blog.wesgibbs.org/2008/4/17/bandwidth-tracking" rel="alternate" type="text/html"/>
    <title>Bandwidth Tracking</title>
<content type="html">
            &lt;p&gt;Like a lot of web applications, &lt;a href=&quot;http://www.madpolitic.com&quot;&gt;MadPolitic&lt;/a&gt; has different levels of user accounts. One of the account differentiators is bandwidth allowance; higher-level accounts have an increased bandwidth limit. To implement this, I needed a way to track bandwidth usage per account. Here&#8217;s how I did it using Apache.&lt;/p&gt;


	&lt;h4&gt;Use CustomLog and cronolog to create and rotate a custom bandwidth log&lt;/h4&gt;


The standard Apache access.log was missing several things I needed in order to track bandwidth.
	&lt;ul&gt;
	&lt;li&gt;the format did not include the host from the request header&lt;/li&gt;
		&lt;li&gt;it also did not include the number of bytes Apache sent back across the network to the client in response to each request&lt;/li&gt;
		&lt;li&gt;the log rotation didn&#8217;t give me a clean history of log files by day&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;To remedy this, I created a CustomLog and used &lt;a href=&quot;http://cronolog.org/&quot;&gt;cronolog&lt;/a&gt; to get some more advanced log rotation. Apache provides log rotation capability out of the box, but the Apache docs themselves &lt;a href=&quot;http://httpd.apache.org/docs/2.0/logs.html#piped&quot;&gt;recommend&lt;/a&gt; cronolog for more flexible logging.&lt;/p&gt;


	&lt;p&gt;Here&#8217;s the CustomLog I created, from my &lt;code&gt;httpd.conf&lt;/code&gt; file&lt;/p&gt;


&lt;pre&gt;
CustomLog &quot;|/usr/local/sbin/cronolog -l /etc/httpd/logs/bandwidth_today -P /etc/httpd/logs/bandwidth_yesterday /etc/httpd/logs/%Y/%m/%d/bandwidth.log&quot; bandwidth env=!dontlog
&lt;/pre&gt;

Apache passes most of the work off to cronolog, which does a few things
	&lt;ul&gt;
	&lt;li&gt;creates a symbolic link called &lt;code&gt;bandwidth_today&lt;/code&gt; to the current bandwidth log file&lt;/li&gt;
		&lt;li&gt;creates a symbolic link called &lt;code&gt;bandwidth_yesterday&lt;/code&gt; to the previous day&#8217;s bandwidth log file&lt;/li&gt;
		&lt;li&gt;defines a spec that indicates how I want the logfiles rotated and stored, in this case, in directories based on the month, day and year&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;After the piped invocation of cronolog, the CustomLog directive has two more parameters. The first, &lt;code&gt;bandwidth&lt;/code&gt;, references a LogFormat I created. More on that in a moment. The last parameter enables the ability to &lt;em&gt;not&lt;/em&gt; log certain requests. For example, if you have Apache serving up other sites or content that you do not want logged, you can add lines like this to your &lt;code&gt;httpd.conf&lt;/code&gt; file&lt;/p&gt;


&lt;pre&gt;
SetEnvIf Host &quot;myblog\.mydomain\.com&quot; dontlog
&lt;/pre&gt;

	&lt;p&gt;and that final parameter to CustomLog makes sure requests to myblog.mydomain.com don&#8217;t wind up in the log.&lt;/p&gt;


	&lt;h4&gt;Create a custom LogFormat&lt;/h4&gt;


	&lt;p&gt;Recall that &lt;code&gt;bandwidth&lt;/code&gt; parameter I passed to the CustomLog directive. It should reference a LogFormat directive that tells Apache how I want each line of the log file to look. By default, the Apache access log is missing the two key pieces of information I needed: the host from the request header, and the number of bytes that Apache sent back across the network to the client.&lt;/p&gt;


	&lt;p&gt;Logging the host was one of the keys to making all this work for my application. That&#8217;s because I use a subdomain-per-account approach, so each account gets a unique subdomain like bob.madpolitic.com. Capturing that host information in the log files along with the bytes transferred would give me all the raw data I needed to map bandwidth usage to accounts.&lt;/p&gt;


	&lt;p&gt;I started by adding those bits into the format and came up with the following&lt;/p&gt;


&lt;pre&gt;
LogFormat &quot;%t %{Host}i %O %h \&quot;%r\&quot; %&amp;gt;s&quot; bandwidth
&lt;/pre&gt;

	&lt;p&gt;You can reference the Apache docs for the &lt;a href=&quot;http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#logformat&quot;&gt;LogFormat directive&lt;/a&gt; for more detail, but in brief, this line tells Apache to log the time (&lt;code&gt;%t&lt;/code&gt;), the contents of the Host: header in the request (&lt;code&gt;%{Host}i&lt;/code&gt;), the bytes sent over the network to the client (&lt;code&gt;%O&lt;/code&gt;), the remote host (&lt;code&gt;%h&lt;/code&gt;), the first line of the &lt;span class=&quot;caps&quot;&gt;HTTP&lt;/span&gt; request, quoted (&lt;code&gt;\&quot;%r\&quot;&lt;/code&gt;), and the &lt;span class=&quot;caps&quot;&gt;HTTP&lt;/span&gt; status of the response (&lt;code&gt;%&amp;gt;s&lt;/code&gt;). Finally, it gives this format a name, &lt;code&gt;bandwidth&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;I now had a log file being written out in a format that I specified that included, most importantly, the host and the number of bytes sent to the client for each request. That log file was being rotated daily and previous logs were stored in a directory structure based on the date. I also had some handy symbolic links to today&#8217;s and yesterday&#8217;s bandwidth log files.&lt;/p&gt;


	&lt;h4&gt;Make Apache write your Ruby code&lt;/h4&gt;


	&lt;p&gt;This worked great. The plan was to fill a log with this information, and have one log file per day. Then I could use a log analyzer and some Ruby to parse through all those log files, compile the bandwidth statistics, and write it all into my application&#8217;s database so that my Rails app could get to it to do things like show the user how much bandwidth they&#8217;ve used. After trying it out for a little while, however, I came up with another idea.&lt;/p&gt;


	&lt;p&gt;Why not have Apache just write the Ruby code for me? I could drop the log analyzer and basically just execute the log file like a Ruby script and have it give me the data in the structure I wanted: a Ruby hash mapping hosts to bytes.&lt;/p&gt;


	&lt;p&gt;I went back to work on my log format and came up with this&lt;/p&gt;


&lt;pre&gt;
LogFormat &quot;bw[\&quot;%{Host}i\&quot;] = (bw[\&quot;%{Host}i\&quot;]) ? bw[\&quot;%{Host}i\&quot;] = bw[\&quot;%{Host}i\&quot;] + %O : bw[\&quot;%{Host}i\&quot;] = %O&quot; bandwidth
&lt;/pre&gt;

	&lt;p&gt;This gave me logs with lines like this&lt;/p&gt;


&lt;pre&gt;
bw[&quot;bob.madpolitic.com&quot;] = (bw[&quot;bob.madpolitic.com&quot;]) ? bw[&quot;bob.madpolitic.com&quot;] = bw[&quot;bob.madpolitic.com&quot;] + 123 : bw[&quot;bob.madpolitic.com&quot;] = 123
bw[&quot;frank.madpolitic.com&quot;] = (bw[&quot;frank.madpolitic.com&quot;]) ? bw[&quot;frank.madpolitic.com&quot;] = bw[&quot;frank.madpolitic.com&quot;] + 3442 : bw[&quot;frank.madpolitic.com&quot;] = 3442
bw[&quot;bob.madpolitic.com&quot;] = (bw[&quot;bob.madpolitic.com&quot;]) ? bw[&quot;bob.madpolitic.com&quot;] = bw[&quot;bob.madpolitic.com&quot;] + 33 : bw[&quot;bob.madpolitic.com&quot;] = 33
&lt;/pre&gt;

	&lt;p&gt;Now I had a file full of Ruby code that kept a hash called &lt;code&gt;bw&lt;/code&gt; which mapped the host to the number of bytes transferred. Each line would check to see if that host already existed as a key in the hash, and if it did, add the bytes to the total already in the hash. Otherwise it would create a new entry in the hash, host =&amp;gt; bytes.&lt;/p&gt;


	&lt;h4&gt;Get the data from the hash into the application database&lt;/h4&gt;


Next I wrote a Ruby script that gets invoked by cron once a day just after midnight. The script does the following
	&lt;ol&gt;
	&lt;li&gt;creates a new empty hash called &lt;code&gt;bw&lt;/code&gt;&lt;/li&gt;
		&lt;li&gt;uses the &lt;code&gt;bandwidth_yesterday&lt;/code&gt; symbolic link to read in yesterday&#8217;s log file all at once to a string. I process bandwidth totals once a day, and remember that this script is being run just after midnight, so I want to process the previous day&#8217;s log&lt;/li&gt;
		&lt;li&gt;sends the &lt;code&gt;eval&lt;/code&gt; message to &lt;code&gt;Kernel&lt;/code&gt; and passes the string that contains the log file along&lt;/li&gt;
		&lt;li&gt;when this is finished, my &lt;code&gt;bw&lt;/code&gt; hash is now populated with &lt;code&gt;host =&amp;gt; bytes&lt;/code&gt; entries&lt;/li&gt;
		&lt;li&gt;the script iterates through each entry in the hash, and for each&lt;/li&gt;
		&lt;li&gt;uses the key (the host) to find an account in my application. Remember that each account gets a unique subdomain, so the host &lt;code&gt;bob.madpolitic.com&lt;/code&gt; would map to bob&#8217;s account&lt;/li&gt;
		&lt;li&gt;looks to see if there is already a row for that account, for the current month, with a bandwidth total and creates one if there is not. This would happen the first time that account is ever used, or at the start of each month&lt;/li&gt;
		&lt;li&gt;adds the value from the current hash entry, which is the bytes transferred for that host for the previous day, to the existing value&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;When it&#8217;s all finished I have a table that is populated with the number of bytes transferred for each account, for each month. The table looks like this&lt;/p&gt;


&lt;pre&gt;
create_table &quot;web_stats&quot;, :force =&amp;gt; true do |t|
  t.column &quot;account_id&quot;,   :integer
  t.column &quot;month&quot;,         :string # stored in a %m%Y format, like 042008
  t.column &quot;bytes&quot;,           :bigint
end
&lt;/pre&gt;

	&lt;p&gt;I&#8217;ve also got all of the historical log files still sitting on my file system (getting backed up once a day) in the event I need to recreate the data or mash it up some other way.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-04-16:7</id>
    <published>2008-04-16T03:05:00Z</published>
    <updated>2008-04-16T03:07:21Z</updated>
    <link href="http://blog.wesgibbs.org/2008/4/16/callback-recursion" rel="alternate" type="text/html"/>
    <title>Callback Recursion</title>
<content type="html">
            &lt;p&gt;I made a clumsy mistake with ActiveRecord callbacks recently. I fixed my mistake, but was left wondering if there is a better way to do it.&lt;/p&gt;


	&lt;p&gt;When I save a specific ActiveRecord object, I need to iterate through all the other instances of that model and flip a flag, saving each one. For example, let&#8217;s say I have a piece of functionality where users can create multiple tasks, but only one task can be active at any one time. So I have a model called &lt;code&gt;Task&lt;/code&gt; and it has an attribute called &lt;code&gt;active&lt;/code&gt;. When a user marks a task as active, I need to go through all their other tasks and make sure they are marked inactive.&lt;/p&gt;


	&lt;p&gt;Initially, I tried to do this by implementing an &lt;code&gt;after_save&lt;/code&gt; callback on the model.&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;after_save :deactivate_other_tasks

def deactivate_other_tasks
  user.tasks.each do |task|
    task.update_attribute(:active, false)
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The problem might be obvious to most, however, I had to write it, run it, and watch it fail to figure out the obvious. As I iterate through each task, every time I call &lt;code&gt;update_attribute&lt;/code&gt;, I&#8217;m triggering the same &lt;code&gt;after_save&lt;/code&gt; callback. This little recursion journey continues until the memory wall is hit.&lt;/p&gt;


	&lt;p&gt;So I scrapped the callback approach and instead overrode &lt;code&gt;Task#active=&lt;/code&gt;&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def active=(arg)
  write_attribute(:active, arg) # go ahead and change the attribute of this object
  if (arg =~ /^true$/i) # case-insensitive match of just the string true
    user.tasks.select { |x| x != self }.each { |x| x.update_attribute(:active, false) }
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;This works great. The problem I have with it is that somewhere down the road, it would be easy for someone not familiar with this model to add a &lt;code&gt;before_save&lt;/code&gt; or &lt;code&gt;after_save&lt;/code&gt; callback for some entirely different reason, and fall into the same recursion trap. I can add some comments at the top of the class&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;# Dear lord, whatever you do, do NOT add any callbacks triggered on
# save. You cannot comprehend the consequences.&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;But that&#8217;s just silly.&lt;/p&gt;


	&lt;p&gt;Is there a Railsy way of doing this? Is there a way to save an ActiveRecord object and selectively indicate that you want to skip all the callbacks in that one instance?&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-04-14:6</id>
    <published>2008-04-14T14:44:00Z</published>
    <updated>2008-04-14T14:45:51Z</updated>
    <link href="http://blog.wesgibbs.org/2008/4/14/who-s-hungry" rel="alternate" type="text/html"/>
    <title>Who's Hungry?</title>
<content type="html">
            &lt;p&gt;I put gates at the top and bottom of my stairs, child-proofed all the cabinets and all the drawers. Guess I forgot the fridge.&lt;/p&gt;


	&lt;p&gt;&lt;img src=&quot;http://lh3.ggpht.com/wes.gibbs/SANk7xJ8fgI/AAAAAAAABYs/Hrx82hGCrMg/s288/IMG_1356.JPG&quot; /&gt;&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-04-14:5</id>
    <published>2008-04-14T13:48:00Z</published>
    <updated>2008-04-14T15:02:17Z</updated>
    <link href="http://blog.wesgibbs.org/2008/4/14/blocks-and-precedence" rel="alternate" type="text/html"/>
    <title>Blocks and Precedence</title>
<content type="html">
            &lt;p&gt;There are two different forms for passing a block to a method in Ruby, one with braces, and one with do/end. I used to think they were equivalent, but recently learned that there is a subtle difference having to do with precedence. As an example&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def block_test(arg1)
    &amp;quot;I received '#{arg1}' and &amp;quot; &amp;lt;&amp;lt; (block_given? ? &amp;quot;a block which yielded '#{yield}'&amp;quot; : &amp;quot;no block&amp;quot;)
end

def speak
    &amp;quot;I've been told to say &amp;quot; &amp;lt;&amp;lt; (block_given? ? yield : &amp;quot;nothing&amp;quot;)
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Looking at the brace form of passing blocks to methods, you can see that whether you surround your arguments with parentheses changes who gets the block&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;block_test speak { &amp;quot;hello&amp;quot; } 
# =&amp;gt; &amp;quot;I received 'I've been told to say hello' and no block&amp;quot;

block_test(speak) { &amp;quot;hello&amp;quot; } 
# =&amp;gt; &amp;quot;I received 'I've been told to say nothing' and a block which yielded 'hello'&amp;quot;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;This is fairly intuitive. However, if you use the do/end form for the block, it gets passed as an argument to block_test whether you use parentheses or not&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;block_test speak do
    &amp;quot;hello&amp;quot;
end
# =&amp;gt; &amp;quot;I received 'I've been told to say nothing' and a block which yielded 'hello'&amp;quot;

block_test(speak) do
    &amp;quot;hello&amp;quot;
end
# =&amp;gt; &amp;quot;I received 'I've been told to say nothing' and a block which yielded 'hello'&amp;quot;&lt;/code&gt;&lt;/pre&gt;
          </content>  </entry>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-04-11:2</id>
    <published>2008-04-11T12:00:00Z</published>
    <updated>2008-04-13T17:48:48Z</updated>
    <link href="http://blog.wesgibbs.org/2008/4/11/a-little-irb-context" rel="alternate" type="text/html"/>
    <title>A Little irb Context</title>
<content type="html">
            &lt;p&gt;When you&#8217;re sitting at your irb prompt, sometimes it can get a little confusing trying to remember the context in which all those commands you&#8217;re entering are executed. We know that anything entered at the prompt in irb is executed in &lt;em&gt;some&lt;/em&gt; context, but it&#8217;s easy to forget what it is since it&#8217;s loaded for you and is not explicit.&lt;/p&gt;


	&lt;p&gt;We know that if we ask irb about itself, it tells us its class is Object&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
&amp;gt;&amp;gt; self.class
=&amp;gt; Object
&lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;So if we take that together with two facts from the pickaxe book:&lt;/p&gt;


&lt;pre&gt;
&quot;class and module definitions are executable code&quot;, and 
&quot;a class definition is executed with that class as the current object&quot; 
&lt;/pre&gt;

	&lt;p&gt;we can begin to cobble together an answer. Great! What was the question again?&lt;/p&gt;


	&lt;p&gt;The question: what is the context of that irb prompt? &lt;br /&gt;
The answer: you are entering code into the class definition of the Object class, and it is being executed in the context of an instance of the Class for Object named &#8216;main&#8217;. Clear? I thought so.&lt;/p&gt;


Sometimes I find it useful to visualize the context of irb using this example:
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Object

    # all of Object's methods defined here

    # Now imagine that your irb prompt is sitting right here, 
    # in this gap in Object's class, right before the final end, 
    # flashing at you, waiting for you to do great things.

    # &amp;gt;&amp;gt;

    # And every time you hit the Return key, the entire class 
    # definition for Object is executed again, with whatever 
    # command(s) you entered at the prompt appended to the 
    # end of the class definition.
  end&lt;/code&gt;&lt;/pre&gt;

This means you can do things like
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Object

    # all of Object's methods defined here

    # &amp;gt;&amp;gt;
    private 
    def foo(arg)
      puts &amp;quot;#{arg}&amp;quot;
    end

    foo(&amp;quot;bar&amp;quot;)
   # And you'll see &amp;quot;bar&amp;quot; output.

    # Now define a class to play around with
    class Fool
      def touch
        &amp;quot;slap!&amp;quot;
      end
    end

    fool = Fool.new
    puts fool.touch

    # And you'll see &amp;quot;slap!&amp;quot;
  end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Obviously this is a gross over-simplification of what irb is. But maybe this little &lt;em&gt;Gedankenexperiment&lt;/em&gt; will help contextualize your irb-ing.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.wesgibbs.org/">
    <author>
      <name>wesgibbs</name>
    </author>
    <id>tag:blog.wesgibbs.org,2008-04-09:1</id>
    <published>2008-04-09T19:37:00Z</published>
    <updated>2008-04-13T18:02:35Z</updated>
    <link href="http://blog.wesgibbs.org/2008/4/9/that-first-line-of-ruby" rel="alternate" type="text/html"/>
    <title>That First Line of Ruby</title>
<content type="html">
            &lt;p&gt;Probably the very first piece of ruby code most of us wrote was some invocation of the &lt;code&gt;puts&lt;/code&gt; method. In those early days, I remember grokking enough to know that &lt;code&gt;puts&lt;/code&gt; added a newline and &lt;code&gt;print&lt;/code&gt; did not and then I moved on.&lt;/p&gt;


	&lt;p&gt;Recently, I was watching a coworker give a demonstration to our team of the facade pattern using ruby. His example worked great, except that the output wasn&#8217;t formatted the way he expected. He had overridden the &lt;code&gt;to_s&lt;/code&gt; method in one of his classes and was using &lt;code&gt;Kernel#p&lt;/code&gt; to output the object.&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Grouper
attr_accessor :taste, :color, :price
  def initialize(taste, color, price)
    @taste, @color, @price = taste, color, price
  end
  def to_s
    &amp;quot;Taste: #{taste}, Color: #{color}, Price: #{price}&amp;quot;
  end
end

p Grouper.new(&amp;quot;good&amp;quot;, &amp;quot;white&amp;quot;, &amp;quot;cheap&amp;quot;)&lt;/code&gt;&lt;/pre&gt;

which yielded
&lt;pre&gt;&lt;code&gt;#&amp;lt;Grouper:0x314494 @taste=&quot;good&quot;, @price=&quot;cheap&quot;, @color=&quot;white&quot;&amp;gt;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;He was expecting his overridden &lt;code&gt;to_s&lt;/code&gt; method to have been invoked, and it wasn&#8217;t.&lt;/p&gt;


	&lt;p&gt;I decided it might be a good idea to go back and dig a little deeper into some of the ways ruby provides for getting output to &lt;code&gt;$stdout&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;To start, let&#8217;s take every newbie&#8217;s favorite method, &lt;code&gt;puts&lt;/code&gt;. So hearkening back to those heady early moments with Ruby, I fired up irb and invoked &lt;code&gt;puts&lt;/code&gt;:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
&amp;gt;&amp;gt; puts &quot;Oi&quot; 
Oi
=&amp;gt; nil
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;What just happened? Well, we know that the &lt;code&gt;puts&lt;/code&gt; message must have a receiver, even though it&#8217;s not apparent from this invocation through irb. To track down what receiver I was sending the &lt;code&gt;puts&lt;/code&gt; message to, I started with ruby info:&lt;/p&gt;


&lt;pre&gt;
ri puts
&lt;/pre&gt;

	&lt;p&gt;which didn&#8217;t get me very far:&lt;/p&gt;


&lt;pre&gt;
IO#puts, IRB::Locale#puts, IRB::Notifier::AbstructNotifier#puts,
IRB::OutputMethod#puts, Kernel#puts, Net::Telnet#puts,
Net::WriteAdapter#puts,
Net::SSH::Service::Process::OpenManager#puts,
Net::SSH::Service::Process::POpen3Manager::SSHStdinPipe#puts,
StringIO#puts, XMP#puts, XMP::StringInputMethod#puts,
Zlib::GzipWriter#puts, TMail::Decoder#puts, TMail::Decoder#puts,
TMail::Encoder#puts, TMail::Encoder#puts
&lt;/pre&gt;

	&lt;p&gt;So which one of these puts was being invoked? If you took the time to read the list, there&#8217;s really only one likely candidate, but still, let&#8217;s try a more direct approach. Back in irb&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
&amp;gt;&amp;gt; self.class
=&amp;gt; Object
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The &#8220;hidden&#8221; receiver of the &lt;code&gt;puts&lt;/code&gt; message is the Object class. If we check Object&#8217;s instance methods&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
&amp;gt;&amp;gt; Object.instance_methods.include?(&quot;puts&quot;)
=&amp;gt; false
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;we see that &lt;code&gt;puts&lt;/code&gt; isn&#8217;t one of them. Let&#8217;s check its privates&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
&amp;gt;&amp;gt; Object.private_methods.include?(&quot;puts&quot;)
=&amp;gt; true
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;and there it is. But &lt;code&gt;Object#puts&lt;/code&gt; wasn&#8217;t one of the results of our ruby info request. To be precise, &lt;code&gt;puts&lt;/code&gt; is actually a private instance method declared by the Kernel module. Remember that the Object class doesn&#8217;t define any instance methods; it gets them all from mixing in the Kernel module. This misled me for some time because the docs show lots of methods for Object. Then I bothered to read the class documentation for Object, which points out&lt;/p&gt;


&lt;pre&gt;    
&quot;Although the instance methods of +Object+ are defined by the +Kernel+ module, we have chosen to document them here for clarity.&quot; 
&lt;/pre&gt;

	&lt;p&gt;Had the opposite effect on me, but oh well. Nonetheless, now we know that the method we&#8217;ve been calling from irb is &lt;code&gt;Kernel#puts&lt;/code&gt;. Back to ri&lt;/p&gt;


&lt;pre&gt;
------------------------------------------------------------ Kernel#puts
     puts(obj, ...)    =&amp;gt; nil
------------------------------------------------------------------------
     Equivalent to

         $stdout.puts(obj, ...)
&lt;/pre&gt;

&lt;code&gt;$stdout&lt;/code&gt; is a pre-defined variable referencing an instance of the class IO. So at long last, with one final stroke of ri, we find the method we&#8217;ve been invoking all this time
&lt;pre&gt;
---------------------------------------------------------------- IO#puts
     ios.puts(obj, ...)    =&amp;gt; nil
------------------------------------------------------------------------
     Writes the given objects to _ios_ as with +IO#print+. Writes a
     record separator (typically a newline) after any that do not
     already end with a newline sequence. If called with an array
     argument, writes each element on a new line. If called without
     arguments, outputs a single record separator.
&lt;/pre&gt;

	&lt;p&gt;And all it does is write out what you pass it, adding the slightest bit of formatting in the form of new lines after each object. (The record separator used is a bit of a mystery.) What if you pass it something other than a string? Then that object&#8217;s &lt;code&gt;to_s&lt;/code&gt; method is used to get the string representation of the object.&lt;/p&gt;


	&lt;p&gt;Let&#8217;s move on to another popular method, &lt;code&gt;print&lt;/code&gt;. As I said at the beginning, I used to just think of &lt;code&gt;print&lt;/code&gt; as being like &lt;code&gt;puts&lt;/code&gt; but without the new line. That is correct, but is not the only difference. When &lt;code&gt;print&lt;/code&gt; is invoked without an explicit receiver in irb, it&#8217;s the IO class that receives the &lt;code&gt;print&lt;/code&gt; message, just like &lt;code&gt;puts&lt;/code&gt;. In the case of &lt;code&gt;print&lt;/code&gt;, however, there is some extra logic that gets applied to the formatting. &lt;code&gt;print&lt;/code&gt; will add the value of the output field separator variable ($,) after each field, and append the value of the output record separator variable ($\) to the end of the output.&lt;/p&gt;


So typically those variables are nil
&lt;pre&gt;&lt;code&gt;
&amp;gt;&amp;gt; print &quot;one&quot;, &quot;two&quot;, &quot;three&quot; 
onetwothree=&amp;gt; nil
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Nothing between the fields, and nothing at the end of the output. If you give those variables values&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
&amp;gt;&amp;gt; $\ = &quot; [louise] &quot; 
&amp;gt;&amp;gt; $, = &quot; [mabel] &quot; 
&amp;gt;&amp;gt; print &quot;one&quot;, &quot;two&quot;, &quot;three&quot; 
one [mabel] two [mabel] three [louise] =&amp;gt; nil
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;To finish, we&#8217;ll look at &lt;code&gt;Object#inspect&lt;/code&gt; and &lt;code&gt;Kernel#p&lt;/code&gt;. The key difference between &lt;code&gt;Object#inspect&lt;/code&gt; and the other methods we&#8217;re looking at is that &lt;code&gt;Object#inspect&lt;/code&gt; does not write anything to &lt;code&gt;$stdout&lt;/code&gt; and returns a String. The other methods all write to &lt;code&gt;$stdout&lt;/code&gt; and return nil.&lt;/p&gt;


	&lt;p&gt;The common use case for &lt;code&gt;Object#inspect&lt;/code&gt; is seeing what the current state of the object is, i.e. what all its instance variables are set to. By default, inspect returns a string comprising the object&#8217;s class and id, and the state of its variables.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
&amp;gt;&amp;gt; g = Grouper.new(&quot;awful&quot;, &quot;white&quot;, &quot;cheap&quot;)
&amp;gt;&amp;gt; g.inspect
=&amp;gt; &quot;#&amp;lt;Grouper:0x3503f4 @color=\&quot;white\&quot;, @taste=\&quot;good\&quot;, @price=\&quot;cheap\&quot;&amp;gt;&quot; 
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;&lt;code&gt;Object#inspect&lt;/code&gt; does some simple formatting, like surrounding strings with quotes. One thing to note is that &lt;code&gt;Object#inspect&lt;/code&gt; does not bother itself with Grouper&#8217;s &lt;code&gt;to_s&lt;/code&gt; method.&lt;/p&gt;


&lt;code&gt;Kernel#p&lt;/code&gt; takes one or more objects as arguments and just iterates through them, calling &lt;code&gt;Object#inspect&lt;/code&gt; for each, and sending the output to &lt;code&gt;$stdout&lt;/code&gt;.
&lt;pre&gt;&lt;code&gt;
&amp;gt;&amp;gt; p({&quot;one&quot; =&amp;gt; 1, &quot;two&quot; =&amp;gt; 2, &quot;three&quot; =&amp;gt; 3}, &quot;Frank&quot;, [&quot;green&quot;, &quot;blue&quot;], 5, Object.new)
{&quot;three&quot;=&amp;gt;3, &quot;two&quot;=&amp;gt;2, &quot;one&quot;=&amp;gt;1}
&quot;Frank&quot; 
[&quot;green&quot;, &quot;blue&quot;]
5
#&amp;lt;Object:0x81790&amp;gt;
=&amp;gt; nil
&lt;/code&gt;&lt;/pre&gt;

So back to my coworkers&#8217; example with the Grouper class. He had used the &lt;code&gt;Kernel#p&lt;/code&gt; method to print out a string representation of his object. &lt;code&gt;Kernel#p&lt;/code&gt; just sends the &lt;code&gt;inspect&lt;/code&gt; message to Grouper and writes the returned string out to &lt;code&gt;$stdout&lt;/code&gt;. At no point does the &lt;code&gt;to_s&lt;/code&gt; message get sent to Grouper. This, however, would have given him what he wanted
&lt;pre&gt;&lt;code&gt;
&amp;gt;&amp;gt; puts Grouper.new(&quot;good&quot;, &quot;white&quot;, &quot;cheap&quot;)
Taste: good, Color: white, Price: cheap
=&amp;gt; nil
&lt;/code&gt;&lt;/pre&gt;

Here&#8217;s a summary of the four methods we looked at
&lt;pre&gt;
                       writes to $stdout | invokes obj.to_s | returns
IO#puts(obj, ...)             YES        |        YES       |   nil
IO#print(obj, ...)            YES        |        YES       |   nil
Object#inspect                NO         |        NO        |   String
Kernel#p(obj, ...)            YES        |        NO        |   nil
&lt;/pre&gt;

	&lt;p&gt;If these don&#8217;t give you the control or formatting you need, then take a look at the PrettyPrint class and its Modules.&lt;/p&gt;
          </content>  </entry>
</feed>
