<?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>Chasing &#187; ruby</title>
	<atom:link href="http://chase.ratchetsoftware.com/tag/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://chase.ratchetsoftware.com</link>
	<description>Chase Gray's blog with solutions to various problems by a curious american Ph.D. student.</description>
	<lastBuildDate>Wed, 09 Jun 2010 05:13:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>Reading Advantage Database Server Files (.ADT) in Ruby</title>
		<link>http://chase.ratchetsoftware.com/2010/02/reading-advantage-database-server-files-adt-in-ruby/</link>
		<comments>http://chase.ratchetsoftware.com/2010/02/reading-advantage-database-server-files-adt-in-ruby/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 01:45:50 +0000</pubDate>
		<dc:creator>chasemgray</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Ruby-ADT]]></category>
		<category><![CDATA[Work]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://chase.ratchetsoftware.com/?p=172</guid>
		<description><![CDATA[I recently received some data in the Advantage Database Server file format (.adt). In the past I have worked with DBF, Access, and .xls. I was able to find some way to retrieve data from these formats using open source software. The open source solutions were much easier to work with, usually not requiring any [...]]]></description>
			<content:encoded><![CDATA[<p>I recently received some data in the <a href="http://www.sybase.com/products/databasemanagement/advantagedatabaseserver">Advantage Database Server</a> file format (.adt).  In the past I have worked with DBF, Access, and .xls.  I was able to find some way to retrieve data from these formats using open source software.  The open source solutions were much easier to work with, usually not requiring any sort of driver installation, etc.</p>
<p>I searched thoroughly for an easy way to retrieve information from this set of .ADT files I was dealing with.  Sybase provides tools to work with the data, but all of them require using their software or drivers developed by them.  I would have settled for this if it wasn&#8217;t such a hassle to figure out how to use them.  I asked the question on <a href="http://stackoverflow.com/questions/2289519/automate-conversion-of-sybase-adt-files-to-sql">Stackoverflow.com</a> and got an answer from one of the employee&#8217;s of Sybase.  While helpful, the suggested Perl driver was one of the things I was avoiding.  I did attempt it and after a little hassle, moved on to creating a simpler solution.</p>
<p><span id="more-172"></span>One solution was to simply use Sybase&#8217;s provided &#8220;<a href="http://devzone.advantagedatabase.com/dz/content.aspx?key=20&amp;Release=13">Advantage Data Architect</a>&#8221; software to open the .ADT files and export them all to SQL.  This is possible with their software, but it would not work for my situation.  The developers of the program outputting these .adt files used a separate embedded database for each new report that was being worked on.  This meant there was hundreds of folders, each containing 30-40 .ADT files making up their own embedded database.  I needed something that could automate the extraction of this data.</p>
<h2>Data Format</h2>
<p>To cut this short, I decided to open up the .ADT files with a hex editor and see if I could get the information I needed out.  I only needed the column names, their types, and the actual rows of data.  To aid anybody else doing something similar to this, I&#8217;ll include some of my notes about the format here:</p>
<ul>
<li>The data is stored at the very end of the file. </li>
<li>The byte offset when the data starts is located at byte 32 and is 32-bits</li>
<li>Byte 24 contains a 32-bit integer specifying the number of rows</li>
<li>Byte 36 contains the a 32-bit number representing the number of bytes each record consumes</li>
<li>The header is 400 bytes</li>
<li>Column information is after the header, before the data.  Each column entry is 200 bytes.</li>
<li>The number of columns can be calculated (data_offset-400)/200</li>
<li>Column names consume the first 128 of each column entry.</li>
<li>Byte 130 contains a 16-bit integer representing the type of data.</li>
<li>Byte 136 contains a 16-bit integer, the length of the field in bytes</li>
<li>Character = 04, Double = 0A, Integer = 0B, Shortint = 0C, CICharacter = 14, Date = 03, Time = 0D, Timestamp = 0E, Autoinc = 0F</li>
</ul>
<p>This was enough information to get what I wanted.</p>
<h2>Ruby-ADT Gem</h2>
<p>I took the existing <a href="http://github.com/infused/dbf">DBF gem</a> by Keith Morrison.  Most of the credit for this gem goes to him as I borrowed the structure heavily from his gem.</p>
<p>I&#8217;ll provide an example of what is now possible with my new ADT gem.  No drivers are required and it&#8217;s as simple as installing the gem.  I&#8217;ll include a snippet of the readme from my <a href="http://github.com/chasemgray/Ruby-ADT">Ruby-ADT gem</a> on github, borrowed heavily again from the DBF gem.</p>
<h3>Installation</h3>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">gem install ruby<span style="color:#006600; font-weight:bold;">-</span>adt</pre></div></div>

<h3>Basic Usage</h3>
<p>Load an ADT file:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'rubygems'</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'adt'</span>
&nbsp;
table = <span style="color:#6666ff; font-weight:bold;">ADT::Table</span>.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;test.adt&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Enumerate all records</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">table.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>record<span style="color:#006600; font-weight:bold;">|</span>          
	<span style="color:#CC0066; font-weight:bold;">puts</span> record.<span style="color:#9900CC;">name</span>          
	<span style="color:#CC0066; font-weight:bold;">puts</span> record.<span style="color:#9900CC;">email</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Load a single record using <tt>record</tt> or <tt>find</tt></p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">table.<span style="color:#9900CC;">record</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">6</span><span style="color:#006600; font-weight:bold;">&#41;</span>
table.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">6</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Attributes can also be accessed through the attributes hash in  original or underscored form or as an accessor method using the underscored name.</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">table.<span style="color:#9900CC;">record</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">4</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">attributes</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;PhoneBook&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
table.<span style="color:#9900CC;">record</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">4</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">attributes</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;phone_book&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
table.<span style="color:#9900CC;">record</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">4</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">phone_book</span></pre></div></div>

<p>Search for records using a simple hash format.  Multiple search  criteria are ANDed. Use the block form of find if the resulting recordset could be  large otherwise all records will be loaded into memory.</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># find all records with first_name equal to Keith</span>
&nbsp;
table.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:all</span>, <span style="color:#ff3333; font-weight:bold;">:first_name</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">'Keith'</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>record<span style="color:#006600; font-weight:bold;">|</span>  
	<span style="color:#CC0066; font-weight:bold;">puts</span> record.<span style="color:#9900CC;">last_name</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># find all records with first_name equal to Keith and last_name equal to Morrison</span>
table.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:all</span>, <span style="color:#ff3333; font-weight:bold;">:first_name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Keith'</span>, <span style="color:#ff3333; font-weight:bold;">:last_name</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">'Morrison'</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>record<span style="color:#006600; font-weight:bold;">|</span>   
	<span style="color:#CC0066; font-weight:bold;">puts</span> record.<span style="color:#9900CC;">last_name</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># find the first record with first_name equal to Keith</span>
&nbsp;
table.<span style="color:#9900CC;">find</span> <span style="color:#ff3333; font-weight:bold;">:first</span>, <span style="color:#ff3333; font-weight:bold;">:first_name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Keith'</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># find record number 10 </span>
&nbsp;
table.<span style="color:#9900CC;">find</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">10</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<h3>Migrating to ActiveRecord</h3>
<p>An example of migrating a DBF book table to ActiveRecord using a  migration:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'adt'</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> CreateBooks <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Migration</span>      
	<span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">up</span>            
		table = <span style="color:#6666ff; font-weight:bold;">ADT::Table</span>.<span style="color:#5A0A0A; font-weight:bold;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'db/adt/books.adt'</span><span style="color:#006600; font-weight:bold;">&#41;</span>            
		<span style="color:#CC0066; font-weight:bold;">eval</span><span style="color:#006600; font-weight:bold;">&#40;</span>table.<span style="color:#9900CC;">schema</span><span style="color:#006600; font-weight:bold;">&#41;</span>        
		table.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>record<span style="color:#006600; font-weight:bold;">|</span>                  
			Book.<span style="color:#9900CC;">create</span><span style="color:#006600; font-weight:bold;">&#40;</span>record.<span style="color:#9900CC;">attributes</span><span style="color:#006600; font-weight:bold;">&#41;</span>            
		<span style="color:#9966CC; font-weight:bold;">end</span>      
	<span style="color:#9966CC; font-weight:bold;">end</span>  
	<span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">down</span>        
		drop_table <span style="color:#ff3333; font-weight:bold;">:books</span>    
	<span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<h3>Limitations and known bugs</h3>
<ul>
<li>ADT is read-only</li>
<li>External index files are not used</li>
<li>Dates are not currently handled correctly.</li>
</ul>
<h2>Future Directions</h2>
<p>I am going to continue working on this library.  I have already heard from a few others that found this useful immediately after I posted it online.  I was surprised people could find it so quickly.  I&#8217;m sure there are bugs.  I would appreciate any problems to be reported to the <a href="http://github.com/chasemgray/Ruby-ADT">Ruby-ADT Github page</a>.  Emails are also welcome, but any issues should be directed to the github page and I&#8217;ll get to them when I can.</p>
</p>
<p>Hope this helps somebody out there dealing with this format.</p>
</p>
<p>- Chase Gray</p>
]]></content:encoded>
			<wfw:commentRss>http://chase.ratchetsoftware.com/2010/02/reading-advantage-database-server-files-adt-in-ruby/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Converting Multiple Microsoft Access Databases into a Single MySQL Database &#8211; Rails, Ruby, MDBTools</title>
		<link>http://chase.ratchetsoftware.com/2009/06/converting-multiple-microsoft-access-databases-into-a-single-mysql-database-rails-ruby-mdbtools/</link>
		<comments>http://chase.ratchetsoftware.com/2009/06/converting-multiple-microsoft-access-databases-into-a-single-mysql-database-rails-ruby-mdbtools/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 21:04:25 +0000</pubDate>
		<dc:creator>chasemgray</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[Work]]></category>
		<category><![CDATA[access]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://chase.ratchetsoftware.com/?p=168</guid>
		<description><![CDATA[Some of the data I&#8217;ve been dealing with lately is in Microsoft Access databases (.mdb files). I&#8217;ve been surprised with the lack of support for manipulating these files outside of Access. There are a couple solutions, but nothing satisfied me needs. The worst data set came to me in a few hundred different .mdb files. [...]]]></description>
			<content:encoded><![CDATA[<p>Some of the data I&#8217;ve been dealing with lately is in Microsoft Access databases (.mdb files).  I&#8217;ve been surprised with the lack of support for manipulating these files outside of Access.  There are a couple solutions, but nothing satisfied me needs.  The worst data set came to me in a few hundred different .mdb files.  It looked like the person that exported the database exported a copy of the database for each unique facility.  So each facility had a file, but the schema for each file was exactly the same.  It was apparent that in order to do any sort of complex queries on the data, the files would have to be combined.  I was recommended a tool called mdbtools by somebody at a local Ruby meetup.  I ended up using this along with Ruby inside of a Rake task to convert all my .mdb files into a single MySQL database.  <span id="more-168"></span></p>
<h3>Prerequisites</h3>
<p>The first thing I needed to do was to successfully configure and compile mdbtools. This probably took the longest as there are a few different version out there.  I had the most success with these instructions from the author&#8217;s git repository, <a href="http://www.automatthew.com/2008/02/how-to-compile-mdbtools-on-mac-os-x.html?showComment=1219246620000">http://www.automatthew.com/2008/02/how-to-compile-mdbtools-on-mac-os-x.html?showComment=1219246620000</a>. I was also able to compile this version on my ubuntu machine pretty easily.  The biggest hangup was with a couple of dependencies.  I also had a weird error where the autogen.sh was not detecting my libtools library, but I knew this was installed.  I commented out this check in the autogen.sh and things all worked, luckily.</p>
<p>Understanding mdb-tools was not very difficult.  It contains various libaries for interfacing with it through C, etc.  The only thing I cared about were the command line tools that it provided, listed <a href="http://mdbtools.sourceforge.net/install/x53.htm">here</a>. The commands I will use in this post are mdb-tables, mdb-schema, mdb-export.</p>
<p>The other requirement is to have a MySQL table created ready with permissions, etc. that will end up holding the data from the combined .mdb files.</p>
<h3>Step 1: Extracting the Schema</h3>
<p>One important thing to note about my situation is that all the .mdb files have the same schema.  Knowing this, I was able to simply find a random .mdb file and base my MySQL schema on this.</p>
<p>I have my .mdb files stored in a shared directory and so within my Rake task I used the following code to grab the first one (I&#8217;m sure there is a better way).</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">first_mdb_file = <span style="color:#996600;">''</span>
<span style="color:#008000; font-style:italic;">#get first mdb file</span>
<span style="color:#CC00FF; font-weight:bold;">Dir</span>.<span style="color:#9900CC;">entries</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;#{RAILS_ROOT}/../shared/system/data_sources/SC/sc_mdb_files/&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>mdb_file<span style="color:#006600; font-weight:bold;">|</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> mdb_file =~ <span style="color:#006600; font-weight:bold;">/</span>\.<span style="color:#9900CC;">mdb</span><span style="color:#006600; font-weight:bold;">/</span>
    first_mdb_file = <span style="color:#996600;">&quot;#{RAILS_ROOT}/../shared/system/data_sources/SC/sc_mdb_files/#{mdb_file}&quot;</span>
    <span style="color:#9966CC; font-weight:bold;">break</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Knowing the path to the first .mdb file the schema can be extracted by getting the result of the following shell command (the code surrounded in backticks is executed on the command line of the system).  The -S flag tells it to santize some of the table names by replacing spaces with underscore, etc.  I needed this for my tables because there were some problems without it.</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">schema_sql = <span style="color:#996600;">`mdb-schema -S #{first_mdb_file} mysql`</span></pre></div></div>

<h3>Step 2: Building the Tables</h3>
<p>Since I&#8217;m doing this in a Rake task in Rails (you could do this in plain ruby), I am using an ActiveRecord connection to interface with my MySQL database.  I have a class called ExternalDatabase that allows me to connect to a different database without modifying the one that my main Rails program uses.  I will list it below, I don&#8217;t remember exactly where I got it from.</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">#Class used to connect to external databases without modifying the exiisting connection used by Rails</span>
<span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#6666ff; font-weight:bold;">Data::ExternalDatabase</span> <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
  <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">abstract_class</span> = <span style="color:#0000FF; font-weight:bold;">true</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">set_source</span><span style="color:#006600; font-weight:bold;">&#40;</span>configuration_name<span style="color:#006600; font-weight:bold;">&#41;</span>
    source = <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">configurations</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;sources&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#91;</span>configuration_name.<span style="color:#5A0A0A; font-weight:bold;">to_s</span><span style="color:#006600; font-weight:bold;">&#93;</span>
    establish_connection source
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">set_configuration</span><span style="color:#006600; font-weight:bold;">&#40;</span>config<span style="color:#006600; font-weight:bold;">&#41;</span>
    source = config
    establish_connection source
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>As you can see, I also have a section in my database.yml where i list connection details for various source databases.  This isn&#8217;t related to this post though.</p>
<p>So, assuming we have this class, we can use the following code to load our new schema into out MySQL database.</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#6666ff; font-weight:bold;">Data::ExternalDatabase</span>.<span style="color:#9900CC;">set_configuration</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:adapter</span>  <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;mysql&quot;</span>,
<span style="color:#ff3333; font-weight:bold;">:host</span>     <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;localhost&quot;</span>,
<span style="color:#ff3333; font-weight:bold;">:username</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> YOUR_DATABASE_USERNAME,
<span style="color:#ff3333; font-weight:bold;">:password</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> YOUR_DATABASE_PASSWORD,
<span style="color:#ff3333; font-weight:bold;">:database</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> YOUR_DATABASE_NAME,
<span style="color:#006600; font-weight:bold;">&#41;</span>
db =  <span style="color:#6666ff; font-weight:bold;">Data::ExternalDatabase</span>.<span style="color:#9900CC;">connection</span> 
&nbsp;
<span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;adding if exists clause to drop tables&quot;</span>
&nbsp;
schema_sql = schema_sql.<span style="color:#CC0066; font-weight:bold;">gsub</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span>DROP TABLE <span style="color:#006600; font-weight:bold;">&#40;</span>.<span style="color:#006600; font-weight:bold;">*</span><span style="color:#006600; font-weight:bold;">&#41;</span>;<span style="color:#006600; font-weight:bold;">/</span>, <span style="color:#996600;">'DROP TABLE IF EXISTS <span style="color:#000099;">\1</span>;'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
schema_sql = schema_sql.<span style="color:#CC0066; font-weight:bold;">gsub</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/--</span>.<span style="color:#006600; font-weight:bold;">*</span>$<span style="color:#006600; font-weight:bold;">/</span>, <span style="color:#996600;">''</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;executing schema sql&quot;</span>
lines = schema_sql.<span style="color:#CC0066; font-weight:bold;">split</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">';'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
lines.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>sql_line<span style="color:#006600; font-weight:bold;">|</span>
  <span style="color:#9966CC; font-weight:bold;">next</span> <span style="color:#9966CC; font-weight:bold;">if</span> sql_line.<span style="color:#9900CC;">blank</span>?
  db.<span style="color:#9900CC;">execute</span><span style="color:#006600; font-weight:bold;">&#40;</span>sql_line<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>The first part builds my database configuration hash that I pass in to ExternalDatabase.  I save the connection into a variable called &#8216;db&#8217;.  One of the important things to note about this and mdb-tools is that it does not check if the table currently exists before trying to drop the table.  So I added a snippet of code that removes the comments and adds &#8216;IF EXISTS&#8217; to the &#8216;DROP TABLE&#8217; clause in the schema sql.</p>
<p>For some reason, trying to execute this entire schema sql string with db.execute causes various errors that I couldn&#8217;t figure out.  By separating the schema sql into individual sql statements terminated with semicolons seemed to fix this problem.  The last bit of code does the separation into lines and executes the sql on the database. After all this, the database should have the correct schema.</p>
<h3>Step 3: Load Data</h3>
<p>One of the last things we want to do is actually load all the data from the different mdb files into the single MySQL database.</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">tables = <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">`mdb-tables #{first_mdb_file}`</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#CC0066; font-weight:bold;">split</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">' '</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#CC00FF; font-weight:bold;">Dir</span>.<span style="color:#9900CC;">entries</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;#{RAILS_ROOT}/../shared/system/data_sources/SC/sc_mdb_files/&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>mdb_file<span style="color:#006600; font-weight:bold;">|</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> mdb_file =~ <span style="color:#006600; font-weight:bold;">/</span>\.<span style="color:#9900CC;">mdb</span><span style="color:#006600; font-weight:bold;">/</span>
    <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Current file: #{mdb_file}&quot;</span>
    tables.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>table<span style="color:#006600; font-weight:bold;">|</span>
      <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Current table: #{table}&quot;</span>
      insert_sql = <span style="color:#996600;">`mdb-export -I -S #{RAILS_ROOT}/../shared/system/data_sources/SC/sc_mdb_files/#{mdb_file} #{table}`</span>
      insert_sql = insert_sql.<span style="color:#CC0066; font-weight:bold;">gsub</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span>;<span style="color:#006600; font-weight:bold;">/</span>, <span style="color:#996600;">','</span><span style="color:#006600; font-weight:bold;">&#41;</span>
      insert_sql = insert_sql.<span style="color:#CC0066; font-weight:bold;">gsub</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span><span style="color:#006600; font-weight:bold;">&#40;</span>.<span style="color:#006600; font-weight:bold;">*</span>?\<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#40;</span>\s<span style="color:#006600; font-weight:bold;">+</span>INSERT<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">/</span>, <span style="color:#996600;">'<span style="color:#000099;">\1</span>;<span style="color:#000099;">\2</span>'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
      lines = insert_sql.<span style="color:#CC0066; font-weight:bold;">split</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">';'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
      lines.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>sql_line<span style="color:#006600; font-weight:bold;">|</span>
        <span style="color:#9966CC; font-weight:bold;">next</span> <span style="color:#9966CC; font-weight:bold;">if</span> sql_line.<span style="color:#9900CC;">blank</span>?
        db.<span style="color:#9900CC;">execute</span><span style="color:#006600; font-weight:bold;">&#40;</span>sql_line<span style="color:#006600; font-weight:bold;">&#41;</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>So the first line runs mdb-tools command line tool &#8216;mdb-tables&#8217; to get a list of the tables separated by spaces.  I could have done this through my previously created schema as well.</p>
<p>This code goes through every .mdb file in my directory and uses mdb-tools to extract the data as sql &#8216;INSERT&#8217; statements from the command-line.</p>
<p>In the inner-most loop, I clean up the returned value from mdb-export because it does not include semi-colons after each INSERT statement.  I also remove any semi-colons before adding any because some of my fields had semi-colons in them.  Again, I separate each INSERT statement into a single statement and execute these individually in the last section of the code.</p>
<p>After all this you should have all your data combined into a single MySQL database.  One problem might exists though.  Certain tables, such as tables that contain general purpose labels, etc. for other tables to refer to, might contain duplicates.  This wouldn&#8217;t have caused a big problem for me because I just needed to extract data, but if you needed to continue using this database you would need to remove the duplicates.</p>
<h3>Final Step: Removing Duplicate Rows</h3>
<p>There seem to be a lot of different ways to remove duplicate rows from a MySQL table.  I wish there was a simple solution, but I couldn&#8217;t find one.  The following code does the following:</p>
<ol>
<li>Create a temporary table that has the same schema as the table we are removing duplicates from.</li>
<li>Insert all distinct rows into this new temporary table.</li>
<li>remove all values from the original table.</li>
<li>Insert all of the rows from the temporary table back into the original table.</li>
<li>Finally, drop the temporary table.</li>
</ol>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;">tables.<span style="color:#5A0A0A; font-weight:bold;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>table<span style="color:#006600; font-weight:bold;">|</span>
  db.<span style="color:#9900CC;">execute</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;CREATE TABLE temp LIKE #{table}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  db.<span style="color:#9900CC;">execute</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;INSERT INTO temp select distinct * FROM #{table}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  db.<span style="color:#9900CC;">execute</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;TRUNCATE #{table}&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  db.<span style="color:#9900CC;">execute</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;INSERT INTO #{table} select * from temp&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  db.<span style="color:#9900CC;">execute</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;DROP TABLE temp&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Thanks for reading, I hope this was helpful to others that have some similar problems.</p>
<p>- Chase</p>
]]></content:encoded>
			<wfw:commentRss>http://chase.ratchetsoftware.com/2009/06/converting-multiple-microsoft-access-databases-into-a-single-mysql-database-rails-ruby-mdbtools/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Treat Google Referred Users Special</title>
		<link>http://chase.ratchetsoftware.com/2009/06/treat-google-referred-users-special/</link>
		<comments>http://chase.ratchetsoftware.com/2009/06/treat-google-referred-users-special/#comments</comments>
		<pubDate>Sun, 07 Jun 2009 05:56:54 +0000</pubDate>
		<dc:creator>chasemgray</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Work]]></category>
		<category><![CDATA[business]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://chase.ratchetsoftware.com/?p=155</guid>
		<description><![CDATA[The content of my main web application, Myhealthcaresource, will contain more than 15000 detailed financial reports for nursing facilities at its future peak.  Each of these reports contains textual information as well as monetary values.  It might list administrator names, employee names/salaries, owners, products or services purchased.  I wanted to have all of this information [...]]]></description>
			<content:encoded><![CDATA[<p>The content of my main web application, <a title="Myhealthcaresource" href="http://www.myhealthcaresource.com">Myhealthcaresource</a>, will contain more than 15000 detailed financial reports for nursing facilities at its future peak.  Each of these reports contains textual information as well as monetary values.  It might list administrator names, employee names/salaries, owners, products or services purchased.  I wanted to have all of this information searchable on Google, without Google caching the page.  I also wanted to let users who came from Google as a result of searching for this information see it without having to log in, but only the page that they found through Google search.<span id="more-155"></span>I&#8217;m going to make this post much shorter and only list the steps I took to solve these problems.</p>
<h3>Problem 1: How to let Google index my data that requires a login</h3>
<p>A prerequisite for this step is to submit sitemaps for your site&#8217;s content to <a href="https://www.google.com/webmasters/tools">Google Webmaster Tools</a>.  Once you have done this, at some point in the future Googlebot will attempt to traverse your page and index its contents (hopefully).</p>
<p>The content on my site requires a user to pay a subscription fee in order to have free reign and browse through whatever they please.  I&#8217;m not very concerned about any single piece of information getting leaked, instead I&#8217;m protecting the resource the site provides as a whole.  By letting Google index your site, you&#8217;re obviously opening up your content to outside viewers that are not logged in.  The extent that you need to protect your content could vary from what my needs are.</p>
<p>What I want is for a user to be able to type their name into Google search engine and find out that they are referenced in the data provided by Myhealthcaresource.com.  So, I need to somehow let Googlebot traverse my site, even through it requires a login by a normal user.</p>
<p>I&#8217;m using Restful Authentication and a role requirement system, so this is how I include this exception.</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> FacilitiesController <span style="color:#006600; font-weight:bold;">&amp;</span>lt; ApplicationController
 require_role <span style="color:#ff3333; font-weight:bold;">:basic</span>, <span style="color:#ff3333; font-weight:bold;">:only</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:show</span>, <span style="color:#ff3333; font-weight:bold;">:unless</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> request.<span style="color:#9900CC;">env</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'HTTP_USER_AGENT'</span><span style="color:#006600; font-weight:bold;">&#93;</span> =~ <span style="color:#006600; font-weight:bold;">/</span>.<span style="color:#006600; font-weight:bold;">*</span>Googlebot.<span style="color:#006600; font-weight:bold;">*/</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>This could vary depending on your authentication system, but the part that will remain the same is the check if the user agent string contains &#8216;Googlebot&#8217;.</p>
<p>That&#8217;s all it takes in order to allow Googlebot to traverse my controlelr that previously required a login.  A potential problem that could come up is that users could &#8216;fake&#8217; their user agent to say &#8216;Googlebot&#8217; and gain access to the site.  This could be a problem for some sites, and we would keep an eye out for this in our logs or through analytics software.  We provide a free trial to all our users before they decide to pay, so uers get a free look at the data already and there is no reason to try to sneak around the site to see it.  We&#8217;re not concerned with this problem, but it could be an issue for others.</p>
<h3>Problem 2: How to prevent Google from caching private pages</h3>
<p>Once Google starts indexes pages of your site that require a login for a normal user, it will also start caching all the sites that it visits.  If you are worried about your internal content getting cached by Google you will want to prevent Google or any other robots from caching.  This is simple and is accomplished by putting the following in the heading of your main layout file.</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&amp;lt;META name=&quot;robots&quot; content=&quot;index,follow,noarchive&quot; /&amp;gt;
&amp;lt;META NAME=&quot;googleBOT&quot; CONTENT=&quot;noarchive&quot; /&amp;gt;</pre></div></div>

<p>When Googlebot reaches your page and sees this tag, it will not cache it.  I have this on the Myhealthcaresource layout, and by searching <a href="http://www.google.com/search?q=myhealthcaresource&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a">myhealthcaresource in google</a> you can see there are no cache links.</p>
<h3>Problem 3: Allowing Users Referred From Google View Content Without Logging In</h3>
<p>When a user sees a link to myhealthcaresource on a set of Google search results, they are most likely to the detailed facility reports that I submitted in a sitemap.  They probably searched their company name or their own and found that they were referred to by my site&#8217;s information.  When someone clicks this link in Google, by default they would get redirected to a page asking them to log in.  This would make almost every user referred from Google resort to their back button immediately.  I noticed this behavior during the period when my site functioned this way.  These users from Google have no idea what kind of information our site offers and they might be a potential customer, so we don&#8217;t want them to leave because we present a log in form when they first arrive.</p>
<p>An alternative is to allow users referred to our site through a Google search to view the entire page.  We decided to do just this.  When they click the link in Google&#8217;s search results they are not asked to log in and they are shown the same page a logged in user would see.  What happens when they try to browse the rest of the private content?  They are asked to log in, but we already have their interest at this point and they are more likely to stay if they found something that was useful to them on the page they landed on.</p>
<p>So how do we accomplish this?  In a similar way that we allowed Googlebot to traverse our pages, we can allow users that were referred from Google to access our page:</p>

<div class="wp_syntax"><div class="code"><pre class="rails" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> FacilitiesController <span style="color:#006600; font-weight:bold;">&amp;</span>lt; ApplicationController
  require_role <span style="color:#ff3333; font-weight:bold;">:basic</span>, <span style="color:#ff3333; font-weight:bold;">:only</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:show</span>, <span style="color:#ff3333; font-weight:bold;">:unless</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> request.<span style="color:#9900CC;">referer</span> =~ <span style="color:#006600; font-weight:bold;">/</span>.<span style="color:#006600; font-weight:bold;">*</span>google.<span style="color:#006600; font-weight:bold;">*/</span> <span style="color:#006600; font-weight:bold;">||</span> request.<span style="color:#9900CC;">env</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">'HTTP_USER_AGENT'</span><span style="color:#006600; font-weight:bold;">&#93;</span> =~ <span style="color:#006600; font-weight:bold;">/</span>.<span style="color:#006600; font-weight:bold;">*</span>Googlebot.<span style="color:#006600; font-weight:bold;">*/</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Of course this code would vary slightly if you are using a different authentication scheme.  The core idea would be the same though.  Now, the potential problem that could come up with this is that a malicious user uses Google to repeatedly access your site by creating clever search queries.  In our case, if a user is this intent on stealing the data, we weren&#8217;t likely to win them as a customer in the first place.  We can also monitor this through analytics tools and if it is abused we will look into an alternative solution.  It could be possible to restrict the number of Google referrals a certain IP can have in a time period or something.</p>
<p>I hope that some of this work can be useful to people who are looking for ways to leverage Google for their dynamically generated login-only content.  We see people come from Google searches every day, and now they stay much longer as a result of these changes.</p>
<p>In a future post, I will briefly talk about another method our site uses to send links to users that allow them to browse the site freely without logging in.  After a certain time period these links expire and the users must sign up to browse the site further.</p>
]]></content:encoded>
			<wfw:commentRss>http://chase.ratchetsoftware.com/2009/06/treat-google-referred-users-special/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Uniq for Array or Hash with a Deeply Nested Structure</title>
		<link>http://chase.ratchetsoftware.com/2009/01/uniq-for-array-or-hash-with-a-deeply-nested-structure/</link>
		<comments>http://chase.ratchetsoftware.com/2009/01/uniq-for-array-or-hash-with-a-deeply-nested-structure/#comments</comments>
		<pubDate>Sun, 04 Jan 2009 23:32:56 +0000</pubDate>
		<dc:creator>chasemgray</dc:creator>
				<category><![CDATA[Projects]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://chase.ratchetsoftware.com/?p=148</guid>
		<description><![CDATA[Most people have had some experience with ruby&#8217;s built in #uniq method for Arrays. Internally, this method finds the unique items in the array by creating a hash internally, and this internal comparison is done with the #eql? method. If an item in the array is a Hash, then #eql? simply uses the object_id, generated [...]]]></description>
			<content:encoded><![CDATA[<p>Most people have had some experience with ruby&#8217;s built in #<a title="Array Uniq Method" href="http://www.ruby-doc.org/core/classes/Array.html#M002237">uniq method for Arrays</a>.  Internally, this method finds the unique items in the array by creating a hash internally, and this internal comparison is done with the #eql? method.  If an item in the array is a Hash, then #eql? simply uses the object_id, generated by <code>the #hash method, </code>to determine whether it is equal to another object in the array.  There are many solutions online each with s light variations and goals.  I found myself in need of a uniq method for an array containing items in an arbitrarily deep nested structure (ie many sub-hashes and arrays). <span id="more-148"></span></p>
<p>I found myself working with some data in a hash generated from scraping a website.  The website had some duplicate content and I didn&#8217;t feel like it was necessary to clutter my scraping code with tests for duplicate content while it was scraping.  After scraping the data and turning it into a hash, I wished to remove the duplicates with some post-processing.  I felt like this should be pretty simple, except that the elements I wanted to test for uniqueness contained a deeply nested structure of hashes and arrays.  Here is an example an element in an array I wanted to uniqify:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&#123;</span>:name <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'bob'</span>, <span style="color:#ff3333; font-weight:bold;">:posts</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:title <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'First Post!'</span> <span style="color:#ff3333; font-weight:bold;">:comments</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:commenter <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Alice'</span>, <span style="color:#ff3333; font-weight:bold;">:text</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'Hi bob!'</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>The #uniq method does not work as expected when there is a Hash element in the array, it only uses the object_id to determine uniqueness. There are some solutions online for dealing with this.</p>
<p>If you know that each element inside the array is a hash with no sub-hashes you can use the solution presented in the answer of <a href="http://stackoverflow.com/questions/181091/how-do-i-get-the-unique-elements-from-an-array-of-hashes-in-ruby">this</a> stackoverflow.com question.  The first solution uses #inject to build a new array with only unique items.  Whether an item is included in the array already or not is determined with the Hash&#8217;s #include method.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">a.<span style="color:#9900CC;">inject</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>result,h<span style="color:#006600; font-weight:bold;">|</span> result <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> h <span style="color:#9966CC; font-weight:bold;">unless</span> result.<span style="color:#9966CC; font-weight:bold;">include</span>?<span style="color:#006600; font-weight:bold;">&#40;</span>h<span style="color:#006600; font-weight:bold;">&#41;</span>; result <span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>The second solution presented in the same post:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">a.<span style="color:#9900CC;">map</span> <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>h<span style="color:#006600; font-weight:bold;">|</span> h.<span style="color:#9900CC;">to_a</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">uniq</span>.<span style="color:#9900CC;">map</span> <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>k,v<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">&#123;</span>k <span style="color:#006600; font-weight:bold;">=&gt;</span> v<span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>This flattens all of your hashes into an array.  It then calls uniq on the resulting array after all the hashes are flattened.  This means that for an item to be unique it must have the same key AND value.  After finding the unique elements, it then maps the items back into a hash.</p>
<p>In <a href="http://mikeburnscoder.wordpress.com/2008/01/18/uniquify-an-array-of-hashes-in-ruby/">this</a> post, Mike Burns solve this problem by redefining #hash and #eql?.  If you are doing this kind of comparison often, this would probably be a better approach.  He does note though, that by doing this the #dup method no longer works as expected.</p>
<p>So it was obvious through searching that I was going to have to figure this out on my own.  I was a little worried that I would have to implement an ugly recursive solution that searches the entire tree to find all duplicates.  While looking into this solution, I felt that it would be very nice if #uniq would accept a block that would allow me to return true if the given parameter is a duplicate, thus removing it from the returned array.  This is not implemented in my current ruby version (1.8.6), but there is an example of how to do this on <a href="http://redhanded.hobix.com/bits/klemmeSSilentHash.html">this blog post</a>.  Hopefully, more (all) of these methods in the ruby core will accept blocks someday.</p>
<p>I began to write a method that would search my tree-like structure of hashes and arrays and I felt like it was a very ugly solution.  I wanted something simple that would just take a line or two and get the job done.  So I showed an example of the problem to my non-computer scientist wife and she said, &#8220;why don&#8217;t you just compare how the two lists look when printed out?&#8221;  I was a little shocked that I hadn&#8217;t thought of this.  It isn&#8217;t the most efficient solution and it relies on the #inspect method, which is probably pretty slow because it has to determine the structure of all the hashes in order to print them in a readable format.   The old solution I was cooking up would also have to traverse the tree, similar to what I expected #inspect was doing.  In addition to the #inspect call, there would be a string comparison for each element.  I was willing to accept both of these for a short elegant solution to my problem.</p>
<p>The issue that came to my mind first was whether hashes get printed out the same way every time.  In Ruby 1.9, it seems that Hashes are going to be stored in the same order that they were entered.  In previous versions, I&#8217;m assuming that they are stored in the order of their generated hash.   This could cause a problem if the data someone was entering could be in different orders.  For my purposes though, the data would be entered in the same order if it was a duplicate.</p>
<p>So, after all of that, to uniqify an array containing a deeply nested structure, I present the following solution:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#CC0066; font-weight:bold;">Array</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> nested_uniq
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">delete_if</span> <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>item<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF; font-weight:bold;">self</span> <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006600; font-weight:bold;">&#91;</span>item<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">any</span>? <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>other_item<span style="color:#006600; font-weight:bold;">|</span> item.<span style="color:#9900CC;">inspect</span> == other_item.<span style="color:#9900CC;">inspect</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> nested_uniq!
    <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">replace</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">nested_uniq</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>I&#8217;ll walk through it because it may seem a bit hard to understand at first.  I go through every element in the array with delete_if to determine if the element should be deleted from the array.  Then, for all elements except the one in question, I check to see if #any? of them are equivalent to the element in question.  This equivalence is determined by doing a string comparison of what the #inspect method returns for that element.</p>
<p>Here is an IRB test</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span>  test = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:hello <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'5'</span>, <span style="color:#ff3333; font-weight:bold;">:test</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:hello <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'10'</span>, <span style="color:#ff3333; font-weight:bold;">:hell</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'5'</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:yeah <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'2'</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:to <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'1'</span>, <span style="color:#ff3333; font-weight:bold;">:yeah</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'8'</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:hello <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'5'</span>, <span style="color:#ff3333; font-weight:bold;">:test</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:hello <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'10'</span>, <span style="color:#ff3333; font-weight:bold;">:hell</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'5'</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:yeah <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'2'</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:test<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:hello<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;10&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:hell</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;5&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:yeah<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;2&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span>, <span style="color:#ff3333; font-weight:bold;">:hello</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;5&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:to<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;1&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:yeah</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;8&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:test<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:hello<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;10&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:hell</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;5&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:yeah<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;2&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span>, <span style="color:#ff3333; font-weight:bold;">:hello</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;5&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> test.<span style="color:#9900CC;">delete_if</span> <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>item<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">&#40;</span>test <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006600; font-weight:bold;">&#91;</span>item<span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">any</span>? <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>other_item<span style="color:#006600; font-weight:bold;">|</span> item.<span style="color:#9900CC;">inspect</span> == other_item.<span style="color:#9900CC;">inspect</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:to<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;1&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:yeah</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;8&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:test<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:hello<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;10&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:hell</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;5&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>, <span style="color:#006600; font-weight:bold;">&#123;</span>:yeah<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;2&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span>, <span style="color:#ff3333; font-weight:bold;">:hello</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;5&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#93;</span></pre></div></div>

<p>Hope this is helpful to someone!  I am very interested to hear suggestions and comments on alternative ways to uniqify an array with elements that have a nested structure.</p>
<p>-Chase</p>
]]></content:encoded>
			<wfw:commentRss>http://chase.ratchetsoftware.com/2009/01/uniq-for-array-or-hash-with-a-deeply-nested-structure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails Database Connection with Block</title>
		<link>http://chase.ratchetsoftware.com/2008/12/rails-database-connection-with-block/</link>
		<comments>http://chase.ratchetsoftware.com/2008/12/rails-database-connection-with-block/#comments</comments>
		<pubDate>Fri, 05 Dec 2008 04:40:01 +0000</pubDate>
		<dc:creator>chasemgray</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://chase.ratchetsoftware.com/?p=141</guid>
		<description><![CDATA[I found myself needing to very quickly connect to an alternate database that was defined in my database.yml like so: alternate_data: adapter: mysql database: alternate_database username: user password: pass host: localhost I was accessing it with something similar to the following: ActiveRecord::Base.establish_connection&#40;ActiveRecord::Base.configurations&#91;&#34;#{state}_data&#34;&#93;&#41; results = connection.execute description_params&#91;:extraction_sql&#93;; #This wasn't actually hard coded, but this is just [...]]]></description>
			<content:encoded><![CDATA[<p>I found myself needing to very quickly connect to an alternate database that was defined in my database.yml like so:</p>

<div class="wp_syntax"><div class="code"><pre class="yaml" style="font-family:monospace;">alternate_data:
    adapter: mysql
    database: alternate_database
    username: user
    password: pass
    host: localhost</pre></div></div>

<p>I was accessing it with something similar to the following:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">establish_connection</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">configurations</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;#{state}_data&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
results = connection.<span style="color:#9900CC;">execute</span> description_params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:extraction_sql</span><span style="color:#006600; font-weight:bold;">&#93;</span>;
<span style="color:#008000; font-style:italic;">#This wasn't actually hard coded, but this is just an example</span>
<span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">establish_connection</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">configurations</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;development&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>The problems with this was that I had to repeat this ugly code everywhere, and if there was an exception thrown while accessing the alternate database it would not revert back to the original before exiting.  So the next request to the server thought the default database was the alternate database.  What I decided would be useful would be to have an &#8220;establish_connection&#8221; method that accepted a block and handle these issues.</p>
<p><span id="more-141"></span></p>
<p>I am going to write about this because I planned to before realizing that in Rails 2.2 the exact same issue is solved already with a much better implementation (of course).  You can find how to solve this problem very elegantly in Rails 2.2 at <a title="Scaling ActiveRecord With MySQLPlus" href="http://www.igvita.com/2008/10/27/scaling-activerecord-with-mysqlplus/">http://www.igvita.com/2008/10/27/scaling-activerecord-with-mysqlplus/</a>.</p>
<p>My implementation is much simpler and I hope that anybody stuck with Rails 2.1 (like me for now) or any previous version can use it temporarily until they can upgrade in the future.</p>
<p>I just wanted a simple block establish_connection so I could write code like the following:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">   establish_temporal_database_connection<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;#{state}_data&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>connection<span style="color:#006600; font-weight:bold;">|</span>
      results = connection.<span style="color:#9900CC;">execute</span> description_params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:extraction_sql</span><span style="color:#006600; font-weight:bold;">&#93;</span>;
    <span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>It would reset the old database connection if something went wrong or when the block was over.</p>
<p>I&#8217;m just going to list a simple module that does this, if anybody wants this in plugin form that actually overrides establish_connection then it isn&#8217;t that difficult to turn this into that:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> ConnectionWithBlock  
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">extended</span><span style="color:#006600; font-weight:bold;">&#40;</span>object<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> object
        extend ClassMethods
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">module</span> ClassMethods
    <span style="color:#9966CC; font-weight:bold;">def</span> establish_temporal_database_connection<span style="color:#006600; font-weight:bold;">&#40;</span>configuration<span style="color:#006600; font-weight:bold;">&#41;</span>
       <span style="color:#008000; font-style:italic;">#save the old connection</span>
       previous_connection = <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">connection</span>
       <span style="color:#008000; font-style:italic;">#establish connection handling a possible exception and going back to original connection</span>
       <span style="color:#9966CC; font-weight:bold;">begin</span>
              <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">establish_connection</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">configurations</span><span style="color:#006600; font-weight:bold;">&#91;</span>configuration.<span style="color:#9900CC;">to_s</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
              <span style="color:#9966CC; font-weight:bold;">yield</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">connection</span><span style="color:#006600; font-weight:bold;">&#41;</span>
       <span style="color:#9966CC; font-weight:bold;">rescue</span> <span style="color:#CC00FF; font-weight:bold;">Exception</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> e
              <span style="color:#CC0066; font-weight:bold;">raise</span> e
       <span style="color:#9966CC; font-weight:bold;">ensure</span>
              <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">establish_connection</span><span style="color:#006600; font-weight:bold;">&#40;</span>ConnectionSpecification.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>previous_connection.<span style="color:#9900CC;">config</span>, previous_connection.<span style="color:#9900CC;">adapter_method</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
       <span style="color:#9966CC; font-weight:bold;">end</span>   
     <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Chase</p>
]]></content:encoded>
			<wfw:commentRss>http://chase.ratchetsoftware.com/2008/12/rails-database-connection-with-block/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails Caching: Dynamic Fragments</title>
		<link>http://chase.ratchetsoftware.com/2008/12/rails-caching-dynamic-fragments/</link>
		<comments>http://chase.ratchetsoftware.com/2008/12/rails-caching-dynamic-fragments/#comments</comments>
		<pubDate>Thu, 04 Dec 2008 03:03:51 +0000</pubDate>
		<dc:creator>chasemgray</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://chase.ratchetsoftware.com/?p=134</guid>
		<description><![CDATA[I am finally getting around to implementing caching on my Rails application that I&#8217;ve been working on adamantly for the past couple of months.  For the time being, I am using a memcached server with simple action and page caching.  I ran into a few problems with my first few attempts at fragment caching and [...]]]></description>
			<content:encoded><![CDATA[<p>I am finally getting around to implementing caching on my Rails application that I&#8217;ve been working on adamantly for the past couple of months.  For the time being, I am using a memcached server with simple action and page caching.  I ran into a few problems with my first few attempts at fragment caching and decided it wasn&#8217;t really necessary for the time being.  I needed a simple method of including small sections of dynamic code in an otherwise static page.  I then wanted to use action caching on the resulting view.  I&#8217;ll outline a simple method I used to achieve this.</p>
<p><span id="more-134"></span></p>
<p>I&#8217;ve been very happy with the results.  Very server intense requests are responding instantly.  This is all great, but caching is usually only appropriate for pages with content that is static for a period of time.  The biggest problem I was having is that there are very small pieces of the pages I wished to cache that are dynamic.  For instance, I want to have a bar at the top that tells the user who is logged in and provides a set of buttons to do things to their profile, etc.  An example of this is shown below:</p>
<div id="attachment_136" class="wp-caption aligncenter" style="width: 478px"><a href="http://chase.ratchetsoftware.com/wp-content/2008/12/picture-2.png" rel="lightbox[134]"><img class="size-full wp-image-136" title="Profile Summary Example" src="http://chase.ratchetsoftware.com/wp-content/2008/12/picture-2.png" alt="Small Dynamic Block Showing User Profile Links" width="468" height="111" /></a><p class="wp-caption-text">Small Dynamic Block Showing User Profile Links</p></div>
<p>So what I needed was an easy way to specify that this small block would be dynamic while still allowing the rest of the view to take advantage of action caching.  I&#8217;m sure there is some plugin that does this and more.  If there is a very good plugin that does just this, I would love to know about it in the comments.  For now, though I am going to provide my simple solution to the problem.</p>
<p>My solution was to create a partial for the profile summary.  I already had the block as a partial to make my view code more DRY.  Instead of this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&lt;%</span>=render <span style="color:#ff3333; font-weight:bold;">:partial</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'profile_summary'</span><span style="color:#006600; font-weight:bold;">%&gt;</span></pre></div></div>

<p>in my view, I replaced it with an AJAX call using Prototype (updated to use Richard Poirier&#8217;s suggestion in the comments):</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">    &lt;div id=&quot;info_panel&quot;&gt;
        <span style="color:#006600; font-weight:bold;">&lt;%</span>= javascript_tag remote_function<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:url</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#ff3333; font-weight:bold;">:controller</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'profile'</span>, <span style="color:#ff3333; font-weight:bold;">:action</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'summary'</span> <span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
    &lt;/div&gt;</pre></div></div>

<p>I then have a controller that can repond to this AJAX request for the profile.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> summary
  render <span style="color:#ff3333; font-weight:bold;">:update</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>page<span style="color:#006600; font-weight:bold;">|</span>
    page.<span style="color:#9900CC;">replace_html</span> <span style="color:#996600;">'info_panel'</span>, <span style="color:#ff3333; font-weight:bold;">:partial</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'/profile/summary'</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Now, every time the page loads, it will load the entire page using the cached version.  It will then make an additional POST request to get the dymanic content.  This would become more complicated if there were many dynamic sections that I needed to load.  I feel like if it was wrapped into a plugin that could automatically handle special dynamic fragments inside a block like this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&lt;%</span>=dynamic_fragment do<span style="color:#006600; font-weight:bold;">%&gt;</span>
   <span style="color:#006600; font-weight:bold;">&lt;%</span>=render <span style="color:#ff3333; font-weight:bold;">:partial</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'profile_summary'</span><span style="color:#006600; font-weight:bold;">%&gt;</span>
<span style="color:#006600; font-weight:bold;">&lt;%</span>end<span style="color:#006600; font-weight:bold;">%&gt;</span></pre></div></div>

<p>it would make it very easy and intuitive to insert dynamic fragments into an otherwise static page.  I do not have the need to implement something like this yet, I am satisfied with my simple solution.  I would be very happy to find a solution where you can specify the dynamic sections of the view instead of only specifying the static portions.  Then the system would magically build the server-side AJAX responses without the user having to do anything.  This allows the use of action_caches which are supposed to be much faster than fragment caching.  While I&#8217;m super busy with my project, stopping to create plugins is not on the priority list, but by writing it all down here I might come back to the best ideas.</p>
<p>I hope anybody looking to insert a small section of dynamic code in an otherwise action cacheable page finds this information useful.</p>
<p>Chase</p>
]]></content:encoded>
			<wfw:commentRss>http://chase.ratchetsoftware.com/2008/12/rails-caching-dynamic-fragments/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
