<?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>Rails on the Run &#187; database</title>
	<atom:link href="http://railsontherun.com/tag/database/feed/" rel="self" type="application/rss+xml" />
	<link>http://railsontherun.com</link>
	<description>Rails experiments by Matt Aimonetti</description>
	<lastBuildDate>Tue, 23 Feb 2010 07:28:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Rails 2.0.2 with few changes</title>
		<link>http://railsontherun.com/2007/12/17/rails-2-0-2-with-few-changes/</link>
		<comments>http://railsontherun.com/2007/12/17/rails-2-0-2-with-few-changes/#comments</comments>
		<pubDate>Mon, 17 Dec 2007 09:52:00 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[contribution]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[release]]></category>
		<category><![CDATA[tasks]]></category>
		<category><![CDATA[update]]></category>

		<guid isPermaLink="false">http://railsontherun.com/2007/12/17/rails-2-0-2-with-few-changes</guid>
		<description><![CDATA[What&#8217;s new? Rails default database is now sqlite3. If you are running Leopard, everything is already setup for you. As DHH mentioned, just &#8220;rails -d mysql yourappname&#8221; if you want to generate a new app preconfigured for MySQL. Sqlite3 is great and if the only reason why you didn&#8217;t give it a try is because [...]]]></description>
			<content:encoded><![CDATA[<h2>What&#8217;s new?</h2>
<ul>
<li>
<p>Rails default database is now sqlite3. If you are running Leopard, everything is already setup for you. As DHH mentioned, just &#8220;rails -d mysql your<em>app</em>name&#8221; if you want to generate a new app preconfigured for MySQL.<br />
Sqlite3 is great and if the only reason why you didn&#8217;t give it a try is because you have to use CocoaMySQL, then check out <a href="http://sqlitebrowser.sourceforge.net/">sqlitebrowser</a></p>
</li>
<li>
<p>Other new feature: rake secret  to generate a key used to encrypt your session. Really useful task when you&#8217;re migrating an app to 2.x</p>
</li>
<li>
<p>To improve performance, some changes were made to the template caching and you have to restart your production server after a template modification.</p>
</li>
<li>
<p>Validates acceptance of still works for non-existent tables . (sorry <a href="http://blog.hasmanythrough.com/">Josh</a>, I won&#8217;t post after 2am, especially when I forget your life changing bug fix <img src='http://railsontherun.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  )</p>
</li>
<li>
<p>Added option to pass proc to ActionController::Base.asset_host for maximum configurability. Example:</p>
</li>
</ul>
<table class="CodeRay">
<tr>
<td class="line_numbers" title="click to toggle" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }">
<pre>1<tt>
</tt>2<tt>
</tt>3<tt>
</tt>4<tt>
</tt><strong>5</strong><tt>
</tt>6<tt>
</tt>7<tt>
</tt></pre>
</td>
<td class="code">
<pre ondblclick="with (this.style) { overflow = (overflow == 'auto' || overflow == '') ? 'visible' : 'auto' }">    <span class="co">ActionController</span>::<span class="co">Base</span>.asset_host = <span class="co">Proc</span>.new { |source|<tt>
</tt>      <span class="r">if</span> source.starts_with?(<span class="s"><span class="dl">'</span><span class="k">/images</span><span class="dl">'</span></span>)<tt>
</tt>        <span class="s"><span class="dl">&quot;</span><span class="k">http://images.example.com</span><span class="dl">&quot;</span></span><tt>
</tt>      <span class="r">else</span><tt>
</tt>        <span class="s"><span class="dl">&quot;</span><span class="k">http://assets.example.com</span><span class="dl">&quot;</span></span><tt>
</tt>      <span class="r">end</span><tt>
</tt>    }</pre>
</td>
</tr>
</table>
<ul>
<li>Finally, I added 2 new rake tasks: db:migrate:redo and db:migrate:reset<br/><br />
db:migrate:redo rolls back your database and then migrates it up. You can define the STEP constant to specify the amount of steps you want to rollback. This task is very useful in development mode when making a modification to the latest migration(s).<br />
db:migrate:reset will drop your database, re create it and migrate it up. Only use this task if you really have to and only in development/test environment.  Use db:reset in production mode since it uses the schema.rb file and won&#8217;t go through the hundreds of migrations you might have.</li>
</ul>
<h2>Changeset</h2>
<p><em>2.0.2</em> (December 16th, 2007)</p>
<ul>
<li>
<p>Changed the default database from mysql to sqlite3, so now running &#8220;rails myapp&#8221; will have a config/database.yml that&#8217;s setup for SQLite3 (which in OS X Leopard is installed by default, so is the gem, so everything Just Works with no database configuration at all). To get a Rails application preconfigured for MySQL, just run &#8220;rails -d mysql myapp&#8221; [DHH]</p>
</li>
<li>
<p>Turned on ActionView::Base.cache<em>template</em>loading by default in config/environments/production.rb to prevent file system stat calls for every template loading to see if it changed (this means that you have to restart the application to see template changes in production mode) [DHH]</p>
</li>
<li>
<p>Introduce <code>rake secret</code> to output a crytographically secure secret key for use with cookie sessions #10363 [revans]</p>
</li>
<li>
<p>Fixed that local database creation should consider 127.0.0.1 local #9026 [parcelbrat]</p>
</li>
<li>
<p>Fixed that functional tests generated for scaffolds should use fixture calls instead of hard-coded IDs #10435 [boone]</p>
</li>
<li>
<p>Added db:migrate:redo and db:migrate:reset for rerunning existing migrations #10431, #10432  [matt]</p>
</li>
<li>
<p>RAILS<em>GEM</em>VERSION may be double-quoted also.  #10443 [James Cox]</p>
</li>
<li>
<p>Update rails:freeze:gems to work with RubyGems 0.9.5.  [Jeremy Kemper]</p>
</li>
<li>
<p>Added delete<em>via</em>redirect and put<em>via</em>redirect to integration testing #10497 [philodespotos]</p>
</li>
<li>
<p>Allow headers['Accept'] to be set by hand when calling xml<em>http</em>request #10461 [BMorearty]</p>
</li>
<li>
<p>Added OPTIONS to list of default accepted HTTP methods #10449 [holoway]</p>
</li>
<li>
<p>Added option to pass proc to ActionController::Base.asset_host for maximum configurability #10521 [chuyeow]. Example:</p>
<p>ActionController::Base.asset_host = Proc.new { |source|<br />
  if source.starts_with?(&#8216;/images&#8217;)<br />
    &#8220;http://images.example.com&#8221;<br />
  else<br />
    &#8220;http://assets.example.com&#8221;<br />
  end<br />
}</p>
</li>
<li>
<p>Fixed that ActionView#file<em>exists? would be incorrect if @first</em>render is set #10569 [dbussink]</p>
</li>
<li>
<p>Added that Array#to<em>param calls to</em>param on all it&#8217;s elements #10473 [brandon]</p>
</li>
<li>
<p>Ensure asset cache directories are automatically created.  #10337 [Josh Peek, Cheah Chu Yeow]</p>
</li>
<li>
<p>render <img src='http://railsontherun.com/wp-includes/images/smilies/icon_mad.gif' alt=':x' class='wp-smiley' /> ml and :json preserve custom content types.  #10388 [jmettraux, Cheah Chu Yeow]</p>
</li>
<li>
<p>Refactor Action View template handlers.  #10437, #10455 [Josh Peek]</p>
</li>
<li>
<p>Fix DoubleRenderError message and leave out mention of returning false from filters.  Closes #10380 [Frederick Cheung]</p>
</li>
<li>
<p>Clean up some cruft around ActionController::Base#head.  Closes #10417 [ssoroka]</p>
</li>
<li>
<p>Ensure optimistic locking handles nil #lock_version values properly.  Closes #10510 [rick]</p>
</li>
<li>
<p>Make the Fixtures Test::Unit enhancements more supporting for double-loaded test cases.  Closes #10379 [brynary]</p>
</li>
<li>
<p>Fix that validates<em>acceptance</em>of still works for non-existent tables (useful for bootstrapping new databases).  Closes #10474 [hasmanyjosh]</p>
</li>
<li>
<p>Ensure that the :uniq option for has_many :through associations retains the order.  #10463 [remvee]</p>
</li>
<li>
<p>Base.exists? doesn&#8217;t rescue exceptions to avoid hiding SQL errors.  #10458 [Michael Klishin]</p>
</li>
<li>
<p>Documentation: Active Record exceptions, destroy<em>all and delete</em>all.  #10444, #10447 [Michael Klishin]</p>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://railsontherun.com/2007/12/17/rails-2-0-2-with-few-changes/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>new plugin to manage your backups</title>
		<link>http://railsontherun.com/2007/07/24/new-plugin-to-manage-your-backups/</link>
		<comments>http://railsontherun.com/2007/07/24/new-plugin-to-manage-your-backups/#comments</comments>
		<pubDate>Tue, 24 Jul 2007 06:18:00 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[active record]]></category>
		<category><![CDATA[ar]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[restore]]></category>
		<category><![CDATA[sake]]></category>

		<guid isPermaLink="false">http://railsontherun.com/2007/07/24/new-plugin-to-manage-your-backups</guid>
		<description><![CDATA[I just released a simple plugin that I use to backup and restore databases instead of using a mysql dump. check out the plugin page File structure will look like that: I use this plugin to backup my apps running in production. When I need to debug an application, I just need to restore the [...]]]></description>
			<content:encoded><![CDATA[<p>I just released a simple plugin that I use to backup and restore databases instead of using a mysql dump.</p>
<p><a href="http://code.google.com/p/ar-backup/">check out the plugin page</a></p>
<p>File structure will look like that:</p>
<p><img src="http://farm2.static.flickr.com/1054/882951034_343db15424_o.jpg" alt="ar-backup"/></p>
<p>I use this plugin to backup my apps running in production. When I need to debug an application, I just need to restore the db locally and debug. The fact that it uses fixtures helps me finding data quickly and I can easily decide to only restore few tables. </p>
<p>I also have a Capistrano recipe to create backups before each deployment.</p>
<p>oohh and the plugin is <a href="http://errtheblog.com/post/6069">Sake</a> compatible, give it a try <img src='http://railsontherun.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Enjoy</p>
]]></content:encoded>
			<wfw:commentRss>http://railsontherun.com/2007/07/24/new-plugin-to-manage-your-backups/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>First Rails patch merged in!</title>
		<link>http://railsontherun.com/2007/05/26/first-rails-merged-in/</link>
		<comments>http://railsontherun.com/2007/05/26/first-rails-merged-in/#comments</comments>
		<pubDate>Sat, 26 May 2007 01:03:00 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[core]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[patch]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[unicode]]></category>
		<category><![CDATA[utf8]]></category>

		<guid isPermaLink="false">http://railsontherun.com/2007/06/14/first-rails-merged-in</guid>
		<description><![CDATA[I&#8217;m quite glad to let you know that my first patch made it to Rails Edge. UPDATE: Ryan Daigle covered the new added features in his blog How cool is that? That&#8217;s a great achievement that I owe to josh Knowles and Josh Susser Josh Knowles and Matt Heidemann from Integrum started working on rake_tasks [...]]]></description>
			<content:encoded><![CDATA[<h2>I&#8217;m quite glad to let you know that my first patch made it to Rails Edge.</h2>
<p>UPDATE: Ryan Daigle covered the new added features in <a href="http://ryandaigle.com/articles/2007/5/29/what-s-new-in-edge-rails-new-database-rake-tasks">his blog</a><br />
How cool is that?</p>
<p>That&#8217;s a great achievement that I owe to <a href="http://joshknowles.com">josh Knowles</a> and <a href="http://hasmanythrough.com">Josh Susser</a></p>
<p><a href="http://joshknowles">Josh Knowles</a> and Matt Heidemann from <a href="http://integrumtech.com">Integrum</a> started working on <a href="http://svn.integrumtech.com/public/plugins/rake_tasks/">rake_tasks</a> a little while ago. I helped them hacking this cool plugin. After a while, we realized that the plugin was getting too big and we decided to split it in two:</p>
<ul>
<li>db_tasks</li>
<li>svn_tasks</li>
</ul>
<p>Without telling the other guys (sorry!), I started <a href="http://groups.google.com/group/rubyonrails-core/browse_thread/thread/194c845ae5678266">discussing</a> merging some of the rake_tasks plugin in Rails core. </p>
<p>I then submitted my patch following <a href="http://hasmanythrough.com/layingtracks">Josh Susser</a> recommendations.</p>
<p>Today, Josh congratulated me on the merge. I&#8217;m quite glad/proud that our work made it to Edge.</p>
<h2>What&#8217;s that patch anyway?</h2>
<p>Here are the 2 features my patch added to the future Rails 2.0:</p>
<ul>
<li>MySQL: create_database takes :charset and :collation options. Charset defaults to utf8. </li>
<li>Add db:create, drop, reset, charset, and collation tasks</li>
</ul>
<p>That means that you cna now do that:</p>
<pre><code>$rails my_app
$rake db:create
$ruby script/server
</code></pre>
<p>That&#8217;s it, you have a working Rails app!! Well, almost, there&#8217;s nothing it in yet but at least your databases are created. Ohh, and your database is unicode, that also means that all your new tables will be utf8.</p>
<p>Enjoy <img src='http://railsontherun.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://railsontherun.com/2007/05/26/first-rails-merged-in/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>db_tasks or how to easily manage your db</title>
		<link>http://railsontherun.com/2007/05/22/dbtasks-intro/</link>
		<comments>http://railsontherun.com/2007/05/22/dbtasks-intro/#comments</comments>
		<pubDate>Tue, 22 May 2007 05:02:00 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[db_tasks]]></category>
		<category><![CDATA[rake]]></category>
		<category><![CDATA[rake task]]></category>
		<category><![CDATA[utf8]]></category>

		<guid isPermaLink="false">http://railsontherun.com/2007/06/14/dbtasks-intro</guid>
		<description><![CDATA[Josh knowles and Matt Heidemann from Integrum and I released few weeks a go a cool plugin called rake_tasks The thing is that the plugin was getting too big when I started hacking the MySQL adapter and adding utf-8 support we figured out it was smarter to split the plugin and create dbtasks and svntasks [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://joshknowles.com">Josh knowles</a> and Matt Heidemann from <a href="http://integrumtech.com">Integrum</a> and I released few weeks a go a cool plugin called <a href="http://svn.integrumtech.com/public/plugins/rake_tasks/">rake_tasks</a> </p>
<p>The thing is that the plugin was getting too big when I started hacking the MySQL adapter and adding utf-8 support we figured out it was smarter to split the plugin and create <a href="http://svn.aimonetti.net/public/plugins/db_tasks/">db<em>tasks</a> and svn</em>tasks</p>
<p>I temporarily hosted db_tasks there:</p>
<p>http://svn.aimonetti.net/public/plugins/db_tasks/</p>
<pre><code>ruby script/plugin install http://svn.aimonetti.net/public/plugins/db_tasks/
</code></pre>
<p>check your Rake tasks:</p>
<ul>
<li><em>rake db:create</em>      Creates the databases defined in your config/database.yml (unless they already exist) You can also specify the charset and collation you want your dbs to use: rake db:create CHARSET=&#8217;latin1&#8242; COLLATION=&#8217;latin1_bin&#8217;)</li>
<li><em>rake db:drop</em>       Drops the database for your currenet RAILS_ENV as defined in config/database.yml</li>
<li><em>rake db:reset</em>       Drops, creates and then migrates the database for your current RAILS_ENV</li>
<li><em>rake db:shell</em>       Launches the database shell using the values defined in config/database.yml</li>
<li><em>rake db:charset</em>    Returns the charset of your current RAILS_ENV database</li>
<li><em>rake db:collation</em>   Returns the collation of your current RAILS_ENV database</li>
<li><em>rake db:update_connection_settings</em>  add the encoding format to each environment in the database.yml file</li>
</ul>
<p>By default, your new databases will be utf8, you can automatically create your databases by typing:</p>
<p>rake db:create</p>
<p>or reset your databases (drop, create, migrate)</p>
<p>rake db:reset</p>
<h2>Another simple plugin for lazy developers.</h2>
]]></content:encoded>
			<wfw:commentRss>http://railsontherun.com/2007/05/22/dbtasks-intro/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing PostgreSQL on Mac</title>
		<link>http://railsontherun.com/2007/05/09/installing-postgresql-on-mac/</link>
		<comments>http://railsontherun.com/2007/05/09/installing-postgresql-on-mac/#comments</comments>
		<pubDate>Wed, 09 May 2007 15:51:00 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[macports]]></category>
		<category><![CDATA[postgresql]]></category>
		<category><![CDATA[setup]]></category>

		<guid isPermaLink="false">http://railsontherun.com/2007/05/09/installing-postgresql-on-mac</guid>
		<description><![CDATA[I&#8217;m working on a Rails project and I need to make sure that our code is compatible with PostgreSQL. I never installed/used before and since I&#8217;m lazy and rely on other people knowledge, I decided to install Postgresql using MacPort. It was actually simpler than I expected. I simply followed this post and almost everything [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working on a Rails project and I need to make sure that our code is compatible with PostgreSQL. I never installed/used before and since I&#8217;m lazy and rely on other people knowledge, I decided to install Postgresql using <a href="http://blog.duncandavidson.com/2006/04/sandboxing_rail.html">MacPort</a>.</p>
<p>It was actually simpler than I expected. I simply followed <a href="http://blog.evanweaver.com/articles/2006/06/26/building-ruby-rails-lighttpd-mysql-and-postgres-on-os-x-tiger">this post</a> and almost everything went ok.</p>
<pre><code>sudo port install postgresql81 +server
</code></pre>
<p>will install postgresql </p>
<pre><code>sudo gem install postgres -- --with-pgsql-include-dir=/opt/local/include/postgresql81 --with-pgsql-lib-dir=/opt/local/lib/postgresql81
</code></pre>
<p>Will do a gem install</p>
<p>Start your server automatically by doing:</p>
<pre><code>sudo launchctl load -w /Library/LaunchDaemons/org.macports.postgresql81-server.plist
sudo launchctl start org.macports.postgresql81-server
</code></pre>
<p>Create a folder for your dbs<br />
    mkdir /opt/local/var/db/pgsql/data</p>
<p>Add pgsql to your path (I use textmate)</p>
<pre><code>mate ~/.profile
</code></pre>
<p>My path looks like that:</p>
<pre><code>export PATH=/opt/local/bin:/opt/local/sbin:/opt/local/apache2/bin:/opt/local/lib/postgresql81/bin/:$PATH

export PGDATA="/opt/local/var/db/pgsql/data"
</code></pre>
<p>restart your shell (or open a new tab) and type<br />
    initdb -D /opt/local/var/db/pgsql/data</p>
<p>Success. You can now start the database server using:</p>
<pre><code>postmaster -D /opt/local/var/db/pgsql/data
</code></pre>
<p>or<br />
    pg_ctl -D /opt/local/var/db/pgsql/data -l logfile start </p>
<p>Now, create your db: $ createdb test -E utf8    or drop your newly created db: $ dropdb test</p>
<p>That&#8217;s it, it was easy.</p>
<p><a href="http://developer.apple.com/internet/opensource/postgres.html">more info from apple</a></p>
]]></content:encoded>
			<wfw:commentRss>http://railsontherun.com/2007/05/09/installing-postgresql-on-mac/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Migrating a legacy app to Rails Part II</title>
		<link>http://railsontherun.com/2007/04/02/migrating-legacy-app-part-2/</link>
		<comments>http://railsontherun.com/2007/04/02/migrating-legacy-app-part-2/#comments</comments>
		<pubDate>Mon, 02 Apr 2007 18:31:00 +0000</pubDate>
		<dc:creator>Matt Aimonetti</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[activeRecord]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[bundle]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[failure]]></category>
		<category><![CDATA[legacy]]></category>
		<category><![CDATA[migration]]></category>
		<category><![CDATA[module]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[RSpec]]></category>
		<category><![CDATA[spec]]></category>
		<category><![CDATA[textmate]]></category>

		<guid isPermaLink="false">http://railsontherun.com/2007/05/22/migrating-legacy-app-part-2</guid>
		<description><![CDATA[In part I I quickly explained what I had to do, my limitations and a potential solution to connect to a legacy database. In this post I&#8217;ll try to go through setting up a plugin for migration and start using RSpec for developing the migration plugin. What we want is to migrate sites using the [...]]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://www.railsontherun.com/2007/3/30/migrating-legacy-app-part-1">part I</a> I quickly explained what I had to do, my limitations and a potential solution to connect to a legacy database.</p>
<p>In this post I&#8217;ll try to go through setting up a plugin for migration and start using <a href="http://rspec.rubyforge.org/">RSpec</a> for developing the migration plugin.</p>
<p>What we want is to migrate sites using the legacy application to our new Rails application. That means that new users won&#8217;t be be migrated. It therefore makes sense not to add the migrating logic to the main application but to create a plugin. (if you are not familiar with Rails plugins check this <a href="http://nubyonrails.com/articles/2006/05/04/the-complete-guide-to-rails-plugins-part-i">blog post from Geoffrey Grosenbach about plugins</a>)</p>
<p>Let&#8217;s create our plugin</p>
<pre><code>./script/generate plugin legacy_migration</code></pre>
<p>Rails should have generated something like that:</p>
<pre><code>legacy_migration
|-- init.rb
|-- install.rb
|-- uninstall.rb
|-- Rakefile
|-- README
|-- lib/
|   |-- legacy_migration.rb
|-- tasks/
|   |-- legacy_migration_tasks.rake
|-- test
|   |-- legacy_migration_test.rb</code></pre>
<p>Since we are going to use RSpec, we can remove the test folder and create a spec folder. In our spec folder, let&#8217;s add some subfolders to organize our files. Let&#8217;s create a fixtures folder to hold, a helpers folder, a migrate folder (we&#8217;ll use that to migrate our legacy database) and finally, a models folder.</p>
<p>Our plugin folder should look more or less like that:</p>
<pre><code>legacy_migration
|-- init.rb
|-- install.rb
|-- uninstall.rb
|-- Rakefile
|-- README
|-- lib/
|   |-- legacy_migration.rb
|-- tasks/
|   |-- legacy_migration_tasks.rake
|-- spec
|   |-- fixtures
|   |-- helpers
|   |-- migrate
|   |-- models</code></pre>
<p>Great, let&#8217;s get started and let&#8217;s create our first spec. We should probably start by migrating users so I&#8217;ll create a new spec in the spec/models folder called legacy_user_spec.rb and add the following code:</p>
<pre><code>require File.dirname(<i>FILE</i>) + '/../helpers/legacy_user_helper'
require File.dirname(<i>FILE</i>) + '/../helpers/spec_helper'</code></pre>
<pre><code>describe "a connection to the legacy application" do
  setup do
    @connection_status = LEGACY.connect
  end
end</code></pre>
<pre><code>it "should be connected to the legacy database" do
  @connection_status.current_database.should == ActiveRecord::Base.configurations<a href="'database'">'legacy'</a>

end</code></pre>
<p>Note that I&#8217;m using RSpec trunk/edge and I use &#8220;describe&#8221; instead of &#8220;context&#8221; and &#8220;it&#8221; instead of &#8220;specify&#8221;. For more information on how to run RSpec edge with TextMate read <a href="http://www.railsontherun.com/2007/3/30/rspec-textmate-bundle-edge">this previous post</a>.</p>
<p>If we look at the code above, we start by requiring 2 helpers, a general helper called spec_helper and a helper just for this spec called legacy_user_helper (we will obviously need to create them otherwise our spec will failed).</p>
<p>Then we start our first spec by describing a connection to the legacy application and we specify that it should be connected to the legacy database.</p>
<p>Here is our setup code:</p>
<pre><code>setup do
  @connection_status = LEGACY.connect
end</code></pre>
<p>What I want is to retrieve a connection status after I connect to our legacy application. To manage the connection to the legacy application we will create a <span class="caps">LEGACY</span> module. We will need to connect to many legacy applications/sites and our module should help us doing that.</p>
<p>Then we can read that our spec checks that we are connected to the legacy database.</p>
<pre><code>it "should be connected to the legacy database" do
  @connection_status.current_database.should == ActiveRecord::Base.configurations<a href="'database'">'legacy'</a>
end</code></pre>
<p>That means we want to compare the connection status to the &#8216;legacy&#8217; environment defined in the database.yml file.</p>
<p>We now need to get this spec to pass.</p>
<p>Let&#8217;s get started by adding a legacy environment to our database.yml and creating our <span class="caps">LEGACY</span> module in our legacy_migration.rb file.</p>
<p>Add the following to your database.yml</p>
<pre><code>legacy:
  adapter: mysql
  database: legacy
  username: root
  password:
  host: localhost</code></pre>
<p>Now, let&#8217;s create the <span class="caps">LEGACY</span> module in our legacy_migration.rb file</p>
<pre><code>
module LEGACY

  # Connect to a Legacy database.
  # Usage:
  # Manual connection: LEGACY.connect(:database => 'legacy-database', :adapter => 'mysql', :username => 'root', :password => '', :host => 'localhost')
  # Auto connection to the database.yml defined legacy DB: LEGACY.connect
  # Connection to any database available in database.yml LEGACY.connect('legacy_test')
  # Connect a class to a specific database: LEGACY.connect(LegacyInstaller, ActiveRecord::Base.configurations['legacy_installer'])
  def self.connect(spec = nil, opt_env = nil)
    case spec
      # Automatically connect to the legacy environment database defined in the database.yml
    when nil
      raise 'Legacy Database not defined' unless defined? ActiveRecord::Base.configurations['legacy']
      LegacyActiveRecord.establish_connection(ActiveRecord::Base.configurations['legacy'])
      # Return the connections status
      LegacyActiveRecord.connection
      # A connection's name from the database.yml can be passed
    when Symbol, String
      if configuration = ActiveRecord::Base.configurations[spec.to_s]
        LegacyActiveRecord.establish_connection(configuration)
      else
        raise "#{spec} database is not configured"
      end
      # Connect a Model to a specific Database
    when Class
      raise 'Environment connection not provided or nil' unless defined? opt_env || opt_env['database'] == nil
      if spec.connection.current_database == opt_env['database']
        spec.connection
      else
        spec.establish_connection(opt_env)
      end
      # An array can be passed to establish the connection
    else
      spec = spec.symbolize_keys
      unless spec.key?(:adapter) then raise "database configuration does not specify adapter" end
        adapter_method = "#{spec[:adapter]}_connection"
        LegacyActiveRecord.establish_connection(spec)
      end
    end
  end</code></pre>
<p>There we go, we have a really cool connect function, we can easily connect to the default legacy environment defined in the database.yml file, we can specify the connection settings, connect to another environment database and even connect one specific class/model to a specific environment. (that will useful since we have many databases). If we wanted to follow the <span class="caps">TDD</span> rules, I shouldn&#8217;t have written so much code&#8230; as a matter of fact, when I worked on this project I did not, but since I don&#8217;t have much time, I won&#8217;t go through the re-factoring steps.</p>
<p>One thing you might have noticed is that we establish a connection between LegacyActiveRecord and the legacy database. (instead of connecting ActiveRecord to the legacy database).</p>
<pre><code>LegacyActiveRecord.establish_connection(ActiveRecord::Base.configurations['legacy'])</code></pre>
<p>The problem is that we didn&#8217;t create the LegacyActiveRecord model yet. Let&#8217;s do that right away. Let&#8217;s add a new folder called models in our lib folder. In the models folder, let&#8217;s create a legacy_active_record.rb file and add the following code:</p>
<pre><code>class LegacyActiveRecord &lt; ActiveRecord::Base
  self.abstract_class = true
end</code></pre>
<p>Cool, now let&#8217;s have fun with our new module, fire the console (./script/console) and try <span class="caps">LEGACY</span>.connect<br />
Here is what we get back:</p>
<pre><code>
    &gt;&gt; <span class="caps">LEGACY</span>.connect
    =&gt; #<activeRecord::ConnectionAdapters::MysqlAdapter:0x32a09d8 @runtime=0.000155925750732422, @config={:password=>nil, :database=&gt;&#8221;legacy&#8221;, :allow_concurrency=&gt;false, :host=&gt;&#8221;localhost&#8221;, :username=&gt;&#8221;root&#8221;, :adapter=&gt;&#8221;mysql&#8221;}, @connection_options=[&#8220;localhost&#8221;, &#8220;root&#8221;, &#8221;&#8221;, &#8220;legacy&#8221;, nil, nil], [...]

</code></pre>
<p>let&#8217;s try to get the database we connected to:</p>
<pre><code>&gt;&gt;LEGACY.connect.current_database
    =&gt; &#8220;legacy&#8221;

</code></pre>
<p>Awesome, we can now get our LegacyActiveRecord model to connect to our legacy database and return the connections status. Let&#8217;s run our specs&#8230;&#8230;&#8230;.. they pass.</p>
<p>Sweet, we setup our migration plugin, got our first spec written, added the code needed to get the spec to pass, I think we are done with <span class="caps">PART 2</span> <img src='http://railsontherun.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://railsontherun.com/2007/04/02/migrating-legacy-app-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

