<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<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/"
	>

<channel>
	<title>activerecord &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/activerecord/</link>
	<description>Feed of posts on WordPress.com tagged "activerecord"</description>
	<pubDate>Sun, 06 Dec 2009 19:08:46 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[ActiveRecord.touch_without_callbacks]]></title>
<link>http://pragmatig.wordpress.com/2009/11/22/activerecord-touch_without_callbacks/</link>
<pubDate>Sun, 22 Nov 2009 20:43:51 +0000</pubDate>
<dc:creator>pragmatig</dc:creator>
<guid>http://pragmatig.wordpress.com/2009/11/22/activerecord-touch_without_callbacks/</guid>
<description><![CDATA[When updating to 2.3.4 I noticed that touch is no longer a simple &#8216;update :updated_at&#8217;, ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>When updating to 2.3.4 I noticed that touch is<br />
no longer a simple &#8216;update :updated_at&#8217;, but a save!,<br />
which caused some code to break<br />
(e.g. <b>touch`ing in after_save == loop</b>)</p>
<p><b>Usage</b></p>
<pre style="font-size:12px;overflow:auto;">
User.first.touch_without_callbacks
User.touch_without_callbacks([User.first.id, User.last.id])
</pre>
<p><b>Install</b><br />
Paste somewhere&#8230;</p>
<pre style="font-size:12px;overflow:auto;">
# Provide .touch as it was in 2.3.2, simply update the :updated_at field.
class ActiveRecord::Base
  def touch_without_callbacks
    now = Time.now.utc
    self.class.touch(id, now)
    self.updated_at = now
  end

  def self.touch_without_callbacks(ids, time=Time.now.utc)
    update_all({:updated_at=&#62;time}, :id=&#62;ids)
  end
end
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Applicazione desktop in ruby con ActiveRecord]]></title>
<link>http://getsmartdan.wordpress.com/2009/11/16/app-ruby-activerecord/</link>
<pubDate>Mon, 16 Nov 2009 11:11:55 +0000</pubDate>
<dc:creator>Daniele</dc:creator>
<guid>http://getsmartdan.wordpress.com/2009/11/16/app-ruby-activerecord/</guid>
<description><![CDATA[In questo periodo di apprendimento di RubyOnRails, ho imparato ad apprezzare le funzionalità di Acti]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>In questo periodo di apprendimento di RubyOnRails, ho imparato ad apprezzare le funzionalità di ActiveRecord, <a title="Orm" href="http://it.wikipedia.org/wiki/Object-relational_mapping" target="_blank">l&#8217;ORM</a> di RoR.</p>
<p>Prendendo spunto da questo <a href="http://blog.aizatto.com/2007/05/27/activerecord-migrations-without-rails/">articolo</a>, ho realizzato lo scheletro di un&#8217;applicazione desktop in ruby, che utilizza ActiveRecord come ORM, Sqlite3 come database, <a href="http://www.fxruby.org/">FxRuby </a>e <a href="http://wxruby.rubyforge.org/wiki/wiki.pl">WxRuby </a> come esempio di interfaccia grafica.</p>
<p>L&#8217;albero delle directory corrisponde ad un progetto di applicazione desktop di <em>NetBeans</em>. Trovo che NetBeans sia un buon IDE per lo sviluppo di applicazioni Ruby e RubyOnRails. Una funzionalità <span style="background-color:#ffffff;">interessante è la possibilità di pacchettizzare l&#8217;applicazione in una rubygem, così da rendere semplice la sua pubblicazione.</span></p>
<p><span style="background-color:#ffffff;">A questo proposito, ho recentemente scoperto <a href="http://gemcutter.org/">gemcutter</a>, un hosting per le <em>rubygem</em> molto semplice da usare.</span></p>
<p><strong><em>Sorgenti</em></strong></p>
<p>Come per ogni progetto NetBeans, i sorgenti dell&#8217;applicazione sono presenti nella directory <em>lib. </em>La logica dell&#8217;applicazione è realizzata nel modulo <em>Head.rb</em>.</p>
<p>use_active_record.rb è uno script che dimostra il funzionamento con ActiveRecord.</p>
<p>Potete scaricare il progetto da <a href="http://dl.dropbox.com/u/2188794/deskopApp.zip">qui </a>o dal widget di Box.net nella sidebar.</p>
<p><strong><em>Configurazione</em></strong></p>
<p>I file di configurazione per l&#8217;utilizzo del database sono presenti nella cartella <em>lib/config</em>.</p>
<p><strong><em>Database</em></strong></p>
<p>Per il mio esempio ho utilizzato SqLite3. Il database presente nei sorgenti contiene 3 tabelle: users, contents e activities.</p>
<p>La gestione del db avviene, come per RoR, per mezzo delle migrations. Queste sono presenti in <em>lib/db/migrate</em>. <span style="background-color:#ffffff;">Le classi dei modelli si trovano in <em>lib/db/model</em>.  Per avviare le migrations è sufficiente eseguire il comando rake all&#8217;interno della cartella <em>lib</em>. Il rakefile presente in quella directory si occuperà del resto.</span></p>
<p><span style="background-color:#ffffff;"><strong><em>Gui</em></strong></span></p>
<p>Per lo sviluppo dell&#8217;interfaccia grafica, ho testato 2 differenti tool di sviluppo: FxRuby e WxRuby. Entrambi sono molto potenti, semplici e facili da configurare. Soprattutto multipiattaforma.</p>
<p>I file relativi ai due esempi sono <em>lib/application_fx.rb</em> per FxRuby e <em>lib/application_wx.rb</em> per WxRuby.</p>
<p><strong><em><br />
</em></strong></p>
<p><span style="background-color:#ffffff;"><br />
</span></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[ActiveRecord: Multiple Database Configuration]]></title>
<link>http://schleichermann.wordpress.com/2009/11/09/activerecord-multiple-database-configuration/</link>
<pubDate>Mon, 09 Nov 2009 04:36:33 +0000</pubDate>
<dc:creator>schleichermann</dc:creator>
<guid>http://schleichermann.wordpress.com/2009/11/09/activerecord-multiple-database-configuration/</guid>
<description><![CDATA[Perhaps you have a web application which not only has a database in which it stores its content but ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Perhaps you have a web application which not only has a database in which it stores its content but also has one to hold logging data (Exceptions, Log Entries).</p>
<p>This can be a common practice used to keep unrelated data separate and to off load the load created by logging data for purely health monitoring reasons. </p>
<p>If you are using Castle ActiveRecord as your ORM (Object Relational Mapping) layer and are familiar with setting it up for one database you may not be familiar with configuring it to handle more than one database for your objects.</p>
<p>ActiveRecord decides which database to send an object to based on a combination of a Abstract base class which inherits from ActiveRecordBase and a separate configuration section for each of those base classes. Each of those base classes must also be registered with ActiveRecord at application startup just like any Entity you plan on using within the application.</p>
<p>Below are the steps you need to take to properly setup your ASP.net web application to use 2 databases.</p>
<p>1. Create a ActiveRecordBase class for each of the databases you will be using. Each entity which inherits from that base class will be mapped to the corresponding database. </p>
<div style="border-bottom:#cccccc 1pt solid;border-left:#cccccc 1pt solid;width:450px;font-family:courier new;background:black;color:white;font-size:10pt;overflow:auto;border-top:#cccccc 1pt solid;font-weight:bold;border-right:#cccccc 1pt solid;padding:1pt;">
<pre style="margin:0;"><span style="color:#cc7832;">public</span> <span style="color:#cc7832;">abstract</span> <span style="color:#cc7832;">class</span> <span style="color:#ffc66d;">ApplicationActiveRecordBase</span><span style="font-weight:normal;">&#60;T&#62; : </span><span style="color:#ffc66d;">ActiveRecordBase</span><span style="font-weight:normal;">&#60;T&#62;{}</span></pre>
</div>
<div style="border-bottom:#cccccc 1pt solid;border-left:#cccccc 1pt solid;width:450px;font-family:courier new;background:black;color:white;font-size:10pt;overflow:auto;border-top:#cccccc 1pt solid;font-weight:bold;border-right:#cccccc 1pt solid;padding:1pt;">
<pre style="margin:0;"><span style="color:#cc7832;">public</span> <span style="color:#cc7832;">abstract</span> <span style="color:#cc7832;">class</span> <span style="color:#ffc66d;">LoggingActiveRecordBase</span><span style="font-weight:normal;">&#60;T&#62; : </span><span style="color:#ffc66d;">ActiveRecordBase</span><span style="font-weight:normal;">&#60;T&#62;{}</span></pre>
</div>
<p>2. Initialize each of the base classes so that ActiveRecord is aware of the classes</p>
<div style="border-bottom:#cccccc 1pt solid;border-left:#cccccc 1pt solid;width:450px;font-family:courier new;background:black;color:white;font-size:10pt;overflow:auto;border-top:#cccccc 1pt solid;font-weight:bold;border-right:#cccccc 1pt solid;padding:1pt;">
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color:#cc7832;">static</span> ActiveRecordInitializer()</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color:#2b91af;font-weight:normal;">IConfigurationSource</span> source = <span style="color:#ffc66d;">ActiveRecordSectionHandler</span><span style="font-weight:normal;">.Instance;</span></pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color:#ffc66d;">ActiveRecordStarter</span><span style="font-weight:normal;">.Initialize(</span></pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; source,</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color:#cc7832;">typeof</span>(<span style="color:#ffc66d;">LoggingActiveRecordBase</span><span style="font-weight:normal;">&#60;&#62;),</span></pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color:#cc7832;">typeof</span>(<span style="color:#ffc66d;">ApplicationActiveRecordBase</span><span style="font-weight:normal;">&#60;&#62;));</span></pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</pre>
</div>
<p>3. All entities belonging to a specific database should inherit from the base class associated with that database in the configuration.</p>
<div style="border-bottom:#cccccc 1pt solid;border-left:#cccccc 1pt solid;width:450px;font-family:courier new;background:black;color:white;font-size:10pt;overflow:auto;border-top:#cccccc 1pt solid;font-weight:bold;border-right:#cccccc 1pt solid;padding:1pt;">
<pre style="margin:0;">&#160;&#160;&#160; [<span style="color:#ffc66d;">DataContract</span>]</pre>
<pre style="margin:0;">&#160;&#160;&#160; [<span style="color:#ffc66d;">ActiveRecord</span>(Table = <span style="color:#a5c25c;">&#34;exceptionentry&#34;</span>)]</pre>
<pre style="margin:0;">&#160;&#160;&#160; <span style="color:#cc7832;">public</span> <span style="color:#cc7832;">class</span> <span style="color:#ffc66d;">ExceptionEntry</span> : <span style="color:#ffc66d;">LoggingActiveRecordBase</span><span style="font-weight:normal;">&#60;</span><span style="color:#ffc66d;">ExceptionEntry</span><span style="font-weight:normal;">&#62;</span></pre>
<pre style="margin:0;">&#160;&#160;&#160; {</pre>
</div>
<p>4. Add configuration sections to the ActiveRecord configuration for each database specifying the ActiveRecordBase class that will be used to identify the database.</p>
<div style="border-bottom:#cccccc 1pt solid;border-left:#cccccc 1pt solid;width:450px;font-family:courier new;background:black;color:white;font-size:10pt;overflow:auto;border-top:#cccccc 1pt solid;font-weight:bold;border-right:#cccccc 1pt solid;padding:1pt;">
<pre style="margin:0;">&#160; &#60;<span style="color:#ff8000;">activerecord</span> isWeb=<span style="color:green;">&#34;true&#34;</span> isDebug=<span style="color:green;">&#34;false&#34;</span> threadinfotype=<span style="color:green;">&#34;Castle.ActiveRecord.Framework.Scopes.HybridWebThreadScopeInfo, Castle.ActiveRecord&#34;</span>&#62;</pre>
<pre style="margin:0;">&#160;</pre>
<pre style="margin:0;">&#160;&#160;&#160; &#60;<span style="color:#ff8000;">config</span> type=<span style="color:green;">&#34;ActiveRecord.BaseClasses.ApplicationActiveRecordBase`1, Data.Core, Vers</span><span style="color:green;">ion=1.0.0.0, Culture=neutral&#34;</span>&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160; &#60;<span style="color:#ff8000;">add</span> key=<span style="color:green;">&#34;hibernate.connection.provider&#34;</span> value=<span style="color:green;">&#34;NHibernate.Connection.DriverConnectionProvider&#34;</span> /&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160; &#60;<span style="color:#ff8000;">add</span> key=<span style="color:green;">&#34;hibernate.dialect&#34;</span> value=<span style="color:green;">&#34;NHibernate.Dialect.MySQLDialect&#34;</span> /&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160; &#60;<span style="color:#ff8000;">add</span> key=<span style="color:green;">&#34;hibernate.connection.driver_class&#34;</span> value=<span style="color:green;">&#34;NHibernate.Driver.MySqlDataDriver&#34;</span> /&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160; &#60;<span style="color:#ff8000;">add</span> key=<span style="color:green;">&#34;hibernate.connection.connection_string&#34;</span> value=<span style="color:green;">&#34;Server=localhost; Database=YOURAPPLICATIONDATABASE; User Id=YOURUSER; Password=YOURPASSWORD&#34;</span> /&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160; &#60;/<span style="color:#ff8000;">config</span>&#62;</pre>
<pre style="margin:0;">&#160;</pre>
<pre style="margin:0;">&#160;&#160;&#160; &#60;<span style="color:#ff8000;">config</span> type=<span style="color:green;">&#34;ActiveRecord.BaseClasses.LoggingActiveRecordBase`1, Data.Core, Version=</span><span style="color:green;">1.0.0.0, Culture=neutral&#34;</span>&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160; &#60;<span style="color:#ff8000;">add</span> key=<span style="color:green;">&#34;hibernate.connection.provider&#34;</span> value=<span style="color:green;">&#34;NHibernate.Connection.DriverConnectionProvider&#34;</span> /&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160; &#60;<span style="color:#ff8000;">add</span> key=<span style="color:green;">&#34;hibernate.dialect&#34;</span> value=<span style="color:green;">&#34;NHibernate.Dialect.MySQLDialect&#34;</span> /&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160; &#60;<span style="color:#ff8000;">add</span> key=<span style="color:green;">&#34;hibernate.connection.driver_class&#34;</span> value=<span style="color:green;">&#34;NHibernate.Driver.MySqlDataDriver&#34;</span> /&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160;&#160;&#160; &#60;<span style="color:#ff8000;">add</span> key=<span style="color:green;">&#34;hibernate.connection.connection_string&#34;</span> value=<span style="color:green;">&#34;Server=localhost; Database=YOURLOGGINGDATABASE; User Id=YOURUSER; Password=YOURPASSWORD&#34;</span> /&#62;</pre>
<pre style="margin:0;">&#160;&#160;&#160; &#60;/<span style="color:#ff8000;">config</span>&#62;</pre>
<pre style="margin:0;">&#160;</pre>
<pre style="margin:0;">&#160; &#60;/<span style="color:#ff8000;">activerecord</span>&#62;&#160; </pre>
</div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Where's the bug?]]></title>
<link>http://dblendea.wordpress.com/2009/11/03/wheres-the-bug/</link>
<pubDate>Tue, 03 Nov 2009 14:37:08 +0000</pubDate>
<dc:creator>bdaniel7</dc:creator>
<guid>http://dblendea.wordpress.com/2009/11/03/wheres-the-bug/</guid>
<description><![CDATA[Where&#8217;s the bug? public virtual void RemoveOfferItems() { for ( int i = 0; i &lt; offerItems.C]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Where&#8217;s the bug?</p>
<pre class="code"><span style="color:blue;">public virtual void </span>RemoveOfferItems()
{
    <span style="color:blue;">for </span>( <span style="color:blue;">int </span>i = 0; i &#60; offerItems.Count; i++ )
    {
        <span style="color:#2b91af;">OfferItem </span>offerItem = offerItems[i];
        log.Trace( <span style="color:#a31515;">"offer item: {0}, {1}"</span>, offerItem.Id, offerItem.Description );

        offerItems.Remove( offerItem );
        offerItem.Delete();
    }
    Save();
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>But don&#8217;t write a test for this…</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[ColdFusion 9 ORM]]></title>
<link>http://benjaminwss.wordpress.com/2009/10/10/coldfusion-9-orm/</link>
<pubDate>Sat, 10 Oct 2009 16:48:20 +0000</pubDate>
<dc:creator>Benjamin Wong</dc:creator>
<guid>http://benjaminwss.wordpress.com/2009/10/10/coldfusion-9-orm/</guid>
<description><![CDATA[When I first heard that ColdFusion 9 will have Object Relational Mapping which is otherwise known as]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>When I first heard that ColdFusion 9 will have Object Relational Mapping which is otherwise known as ORM baked in, I really did not know what to make of it. While I really did like the idea of portable SQL agnostic DAO code, I dreaded the configuration hell that I encountered with Hibernate and NHibernate. While I did have an okay experiance with the Castle Project&#8217;s ActiveRecord implementation of NHibernate, it did not feel very intuitive, at least to me.</p>
<p>Today I spent the better part of the day coding with the new release of ColdFusion and I was blown away with how much it has improved, particularly when used in conjunction with the Eclipse based ColdFusion Builder/Bolt IDE. I particularly love the new ColdFusion(CF) Builder IDE, it looks very polished and has code completion capabilities that felt more like Visual Studio which is a step up from cfeclipse. ColdFusion Builder also has very good integration with ColdFusion servers as it now can start, stop and monitor the ColdFusion servers which is a very big step up. Previously I had to jump between the CF Web Admin/CF Server Monitor and Eclipse/Dreamweaver when I was doing CF development which is very tedious. With this now I can do most of the stuff from within CF Builder which makes life very easy. I tried installing it on my instance of Eclipse that has Flex Builder 3 and it works great. I smell fun times on the horizon when coding apps.</p>
<p>Now back to the main point of this post, Adobe&#8217;s implementation of Hibernate which in true CF tradition, is very intuitive and simple. I was seriously having loads of fun playing with it. Here is some of the stuff I did today :</p>
<p>* I will be putting in my 2 cents/commentary on the benefits I see as comments in the code as I believe it is easier to understand that way.</p>
<p style="text-align:center;"><strong> </strong></p>
<div id="attachment_25" class="wp-caption aligncenter" style="width: 523px"><strong><strong><img class="size-full wp-image-25  " title="Application.cfc" src="http://benjaminwss.wordpress.com/files/2009/10/10102009_104428-pm.jpg" alt="Application.cfc" width="513" height="292" /></strong></strong><p class="wp-caption-text">Application.cfc</p></div>
<div id="attachment_30" class="wp-caption aligncenter" style="width: 580px"><img class="size-full wp-image-30" title="Books.cfc" src="http://benjaminwss.wordpress.com/files/2009/10/10112009_122619-am.jpg" alt="Books.cfc" width="570" height="592" /><p class="wp-caption-text">Books.cfc</p></div>
<div id="attachment_31" class="wp-caption aligncenter" style="width: 580px"><img class="size-full wp-image-31" title="Writers.cfc" src="http://benjaminwss.wordpress.com/files/2009/10/writerscfc.jpg" alt="Writers.cfc" width="570" height="458" /><p class="wp-caption-text">Writers.cfc</p></div>
<div id="attachment_32" class="wp-caption aligncenter" style="width: 329px"><img class="size-full wp-image-32" title="index.cfm" src="http://benjaminwss.wordpress.com/files/2009/10/indexcfm.jpg" alt="index.cfm" width="319" height="141" /><p class="wp-caption-text">index.cfm</p></div>
<p style="text-align:center;">
<div id="attachment_33" class="wp-caption aligncenter" style="width: 580px"><img class="size-full wp-image-33 " title="Sample Output" src="http://benjaminwss.wordpress.com/files/2009/10/sampleoutput.jpg" alt="Sample Output" width="570" height="223" /><p class="wp-caption-text">Sample Output</p></div>
<p>As you can see above, it is is really easy to retrieve items from the database now with the new ORM framework baked in. The entityLoad(&#8220;Writers&#8221;) method basically did this :</p>
<blockquote><p>SELECT a.*, b.* FROM Authors a INNER JOIN Books B ON A.AuthorID = B.AuthorID</p></blockquote>
<p>Notice that now it is possible to write ColdFusion Components totally based on CFScript which is quite close to ActionScript/JavaScript/ECMAScript. I person love option of writing classes in CFScript but I still think that CFML still has its place. I know I for one prefer to loop though collections using cfloop.</p>
<p>I will blog more about other CF 9 ORM methods and setups in the days to come.</p>
<p><strong> </strong></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Rails Finders I: Selecting a Random Model]]></title>
<link>http://railsist.wordpress.com/2009/10/06/rails-finders-i-selecting-a-random-model/</link>
<pubDate>Tue, 06 Oct 2009 16:26:26 +0000</pubDate>
<dc:creator>Joseph Weissman</dc:creator>
<guid>http://railsist.wordpress.com/2009/10/06/rails-finders-i-selecting-a-random-model/</guid>
<description><![CDATA[Ever wanted to pull just one random model from the database? Needed complex finders or ugly workarou]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><img class="alignnone size-full wp-image-31" title="bigstockphoto_Translucent_Blue_Die_9104" src="http://railsist.wordpress.com/files/2009/10/bigstockphoto_translucent_blue_die_9104.jpg" alt="bigstockphoto_Translucent_Blue_Die_9104" width="426" height="319" /></p>
<p>Ever wanted to pull just one random model from the database? Needed complex finders or ugly workarounds? <a href="http://pastie.org/647860">Here&#8217;s a tiny extension of ActiveRecord::Base which adds in the &#8216;missing&#8217; random finders</a>. Try popping that snippet into <em>config/initializers</em>, naming it something useful like <em>supply_random_finders.rb</em>. </p>
<p>Now you&#8217;ve got</p>
<p><code>MyModel.random # pull a random instance of MyModel</code></p>
<p>on any model extending ActiveRecord::Base, as well as the more verbose</p>
<p><code>MyModel.find :random</code></p>
<p>We can use even add conditions to the random search:</p>
<p><code>MyModel.find :random, :conditions =&#62; ["created_at &#60;= ?", 2.weeks.ago]</code></p>
<p>Of course this incurs the normal performance hit on conditional searches, whereas using <code>MyModel.random</code> allows us to utilize the fact that we know how many models are in the database already. This technique also works alongside named scopes.</p>
<p><strong>Update:</strong></p>
<p>While we&#8217;re on the subject of randomness, <a href="http://pastie.org/647859">here&#8217;s a nice extension to Time which allows the generation of random dates and times</a>. I came across it in a Danish fork of Faker, and for all I know this may be integrated into the normal Faker by now. But at any rate it seems to provide a nice, clean way to generate random dates. Enjoy!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[DataMapper versus ActiveRecord]]></title>
<link>http://mauricioszabo.wordpress.com/2009/10/06/datamapper-versus-activerecord/</link>
<pubDate>Tue, 06 Oct 2009 14:00:17 +0000</pubDate>
<dc:creator>Maurício Szabo</dc:creator>
<guid>http://mauricioszabo.wordpress.com/2009/10/06/datamapper-versus-activerecord/</guid>
<description><![CDATA[Outro dia, tive um problema chatíssimo com o ActiveRecord: eu precisava criar um código de autentici]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Outro dia, tive um problema chatíssimo com o ActiveRecord: eu precisava criar um código de autenticidade, que conteria várias matrículas, que conteria várias disciplinas. O problema é o seguinte: Essas matrículas só seriam válidas se, por exemplo, o total de créditos das disciplinas não ultrapassassem um determinado número. Logo, resolvi fazer a validação no modelo de autenticidade, da seguinte forma:</p>
<pre class="brush: ruby;">
class Autenticidade &#60; ActiveRecord::Base
  MAX_CREDITOS = 40
  has_many :matriculas
  has_many :disciplinas, :through =&#62; :matriculas
  validate :credito_alto?

  def credito_alto?
    total = disciplinas.inject(0) { &#124;r, v&#124; r += v.creditos }
    errors.add(:disciplinas, 'créditos acima do permitido') if total &#62; MAX_CREDITOS
  end
end

class Matricula &#60; ActiveRecord::Base
  belongs_to :disciplina
  belongs_to :autenticidade
end

class Disciplina &#60; ActiveRecord::Base
end
</pre>
<p>Ok, o problema agora é o seguinte: Se eu crio uma autenticidade, com o parâmetro :disciplina_ids =&#62; [1, 2], por exemplo, e a autenticidade<strong> não é</strong> válida, nenhuma nova matrícula é criada &#8211; como deveria ser. Agora, se eu atualizo uma autenticidade, com o  autenticidade.update_attributes( :disciplina_ids =&#62; [1, 2]), e essa autenticidade não é válida, o ActiveRecord <strong>salva</strong> as matrículas. Nesse caso, eu tenho uma inconsistência na base de dados feia &#8211; e precisava encontrar uma alternativa que não envolvesse muitos hacks, coisa que ainda não encontrei. Mas isso me estimulou a pesquisar o DataMapper.</p>
<p><!--more--></p>
<p>O <a href="http://datamapper.org/" target="_blank">DataMapper</a> é um ORM assim como o ActiveRecord &#8211; porém com um diferencial que (para alguns) é interessante: Ele só lança os comandos SQL quando você precisa. Nossa autenticidade (fora as validações) ficaria assim:</p>
<pre class="brush: ruby;">
class Autenticidade
  include DataMapper::Resource

  MAX_CREDITOS = 40
  property :id, Serial
  property :codigo_autenticidade, String
  has n, :matriculas
  has n, :disciplinas, :through =&#62; :matriculas
end
</pre>
<p>Para alguns, é uma vantagem declarar as propriedades no próprio código &#8211; dizem que é mais simples de ver o que há nas suas tabelas. Eu, discordo categoricamente disso &#8211; o código-fonte não deveria fazer o que a documentação faz (se você não tem um dicionário de dados, é culpa sua, não do ActiveRecord). Mas uma coisa legal é: Se vc fizer, por exemplo: <strong>a = Autenticidade.all[0]</strong>, o DataMapper gera apenas o SQL que você precisaria (nesse caso, <strong>SELECT * FROM autenticidades LIMIT 1</strong>). Isso funciona, de acordo com a documenação do DataMapper, inclusive para relações:</p>
<pre class="brush: ruby;">
autenticidades = Autenticidade.all #Não gera nenhum SQL ainda
autenticidades.each do &#124;autenticidade&#124; #Gera um SELECT * FROM autenticidades
  p autenticidade.matriculas #Gera um SELECT para listar TODAS as matrículas de TODAS as autenticidades, apenas na primeira iteração
end
</pre>
<p>Ok, isso elimina o tal do problema n+1 (No ActiveRecord, isso geraria um SELECT para cada autenticidade). O problema é: isso funciona muito bem, mas no <strong>has n, :through</strong>, o problema do n+1 existe! E, para piorar, um <strong>Autenticidade.all :include =&#62; :disciplinas</strong> simplesmente não existe, logo eu não tenho como sair desse erro. No fim, a vantagem virou uma desvantagem.</p>
<p>Outra vantagem que eu tinha visto era a possibilidade de criar adaptadores para coisas que não são bases de dados relacionais &#8211; imagine, por exemplo, você usando o DataMapper como um ORM para LDAP, MySQL, REST e YAML, tudo ao mesmo tempo &#8211; fazer associações com isso seria uma maravilha, falar que seu usuário do MySQL tem uma entrada LDAP, usando as associações do próprio DataMapper. Porém, mais uma vez, as coisas não funcionaram muito bem: <strong>has n</strong> só funciona quando as bases de dados estão no mesmo adaptador, talvez para otimizar os SQLs com JOINs, etc. Logo, mais uma vantagem que eu vi foi sub-utilizada.</p>
<p>No fim, a única vantagem que o DataMapper me deu foi a possibilidade de fazer isso aqui:</p>
<pre class="brush: ruby;">
autenticidade = Autenticidade.first
autenticidade.disciplinas &#60;&#60; Disciplina.get(:id =&#62; 1)
autenticidade.disciplinas &#60;&#60; Disciplina.get(:id =&#62; 2)
autenticidade.save #Se for falso, NÃO salva as disciplinas
</pre>
<p>Pois é, eu gostaria mais de ver as vantagens do DataMapper no ActiveRecord do que o inverso&#8230;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[List of the greates features introduced in Rails 2.*]]></title>
<link>http://doesitworks.wordpress.com/2009/10/05/about-what-new-features-you-should-be-aware-since-rails-2-1/</link>
<pubDate>Mon, 05 Oct 2009 17:03:25 +0000</pubDate>
<dc:creator>mikegim</dc:creator>
<guid>http://doesitworks.wordpress.com/2009/10/05/about-what-new-features-you-should-be-aware-since-rails-2-1/</guid>
<description><![CDATA[Rails (2.1, 2.2, 2.3) The list of great features that was introduced in rails ( since  2.0 was intro]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h1>Rails (2.1, 2.2, 2.3)</h1>
<p>The list of great features that was introduced in rails ( since  2.0 was introduced)</p>
<h2>Core, Railties &#8230;</h2>
<ul>
<li>ruby 1.9.1</li>
<li>JRuby 1.3.1</li>
<li>RailsEngines built in <a href="http://asciicasts.com/episodes/149-rails-engines">(o)</a></li>
<li>Gem menagement (with vendor option)</li>
<li>RailsMetal <a href="http://asciicasts.com/episodes/150-rails-metal">(o)</a></li>
<li>rack integration <a href="http://asciicasts.com/episodes/151-rack-middleware">(o)</a></li>
<li>application template <a href="http://asciicasts.com/episodes/148-app-templates-in-rails-2-3">(o)</a></li>
</ul>
<h2>ActionView</h2>
<ul>
<li>internationalization <a href="http://guides.rubyonrails.org/i18n.html">(o)</a> &#38; views localization <a href="http://guides.rubyonrails.org/2_3_release_notes.html#localized-views">(o)</a> &#38; partial scoping <a href="http://guides.rubyonrails.org/2_3_release_notes.html#partial-scoping-for-translations">(o)</a></li>
<li>nested object forms <a href="http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes">(o)</a></li>
<li>smart partial rendering <a href="http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-render-stops-being-high-maintenance">(o)</a></li>
<li>template loading <a href="http://guides.rubyonrails.org/2_3_release_notes.html#a-note-about-template-loading">(o)</a></li>
</ul>
<h2>ActionController</h2>
<ul>
<li>method arrays for member or collection routes <a href="http://guides.rubyonrails.org/2_2_release_notes.html#method-arrays-for-member-or-collection-routes">(0)</a></li>
<li>resources with specific actions<a href="http://guides.rubyonrails.org/2_2_release_notes.html#resources-with-specific-actions"> (o)</a></li>
<li>simplifying of render <a href="http://ryandaigle.com/articles/2008/11/20/what-s-new-in-edge-rails-render-stops-being-high-maintenance">(o)</a></li>
<li>application.rb -&#62; application_controller.rb</li>
<li>http digest authntication <a href="http://ryandaigle.com/articles/2009/1/30/what-s-new-in-edge-rails-http-digest-authentication">(o)</a></li>
<li>lazy load of sessions</li>
</ul>
<h2>ActiveRecord</h2>
<ul>
<li>transactional migrations (multi-step)</li>
<li>database connection pools<a href="http://guides.rubyonrails.org/2_2_release_notes.html#connection-pooling"> (o)</a></li>
<li>nested transactions <a href="http://guides.rubyonrails.org/2_3_release_notes.html#nested-transactions">(o)</a></li>
<li>named scopes <a href="http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality">(o)</a></li>
<li>dynamic scopes <a href="http://ryandaigle.com/articles/2008/12/29/what-s-new-in-edge-rails-dynamic-scope-methods">(o)</a></li>
<li>callbacks with multiple conditions <a href="http://guides.rubyonrails.org/2_3_release_notes.html#multiple-conditions-for-callbacks">(o)</a></li>
<li>hashes for join table conditions <a href="http://guides.rubyonrails.org/2_2_release_notes.html#hashes-for-join-table-conditions">(o)</a></li>
<li>nested attributess <a href="http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes">(o)</a></li>
<li>default scope <a href="http://ryandaigle.com/articles/2008/11/18/what-s-new-in-edge-rails-default-scoping">(o)</a></li>
<li>batch processing <a href="http://ryandaigle.com/articles/2009/2/23/what-s-new-in-edge-rails-batched-find">(o)</a></li>
<li>introduced :having option <a href="http://guides.rubyonrails.org/2_3_release_notes.html#find-with-having">(o)</a></li>
<li>reconenct mysql connections <a href="http://guides.rubyonrails.org/2_3_release_notes.html#reconnecting-mysql-connections">(o)</a></li>
<li>dirty tracking <a href="http://ryandaigle.com/articles/2008/3/31/what-s-new-in-edge-rails-dirty-objects">(o)</a></li>
<li>seed data <a href="http://asciicasts.com/episodes/179-seed-data">(o)</a></li>
</ul>
<h2>ActiveSupport</h2>
<ul>
<li>time zones <a href="http://ryandaigle.com/articles/2008/1/25/what-s-new-in-edge-rails-easier-timezones">(o)</a></li>
<li>methods memoization <a href="http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization">(o)</a></li>
<li>delegate with prefix <a href="http://guides.rubyonrails.org/2_2_release_notes.html#delegates-with-prefixes">(o)</a></li>
<li>enumerable (many?)</li>
</ul>
<h2>Action Mailer</h2>
<ul>
<li>layouts <a href="http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts">(o)</a></li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Building your own ActiveRecord validation macros with validates_each]]></title>
<link>http://codeshooter.wordpress.com/2009/09/28/building-your-own-activerecord-validation-macros-with-validates_each/</link>
<pubDate>Mon, 28 Sep 2009 12:31:05 +0000</pubDate>
<dc:creator>Maurício Linhares</dc:creator>
<guid>http://codeshooter.wordpress.com/2009/09/28/building-your-own-activerecord-validation-macros-with-validates_each/</guid>
<description><![CDATA[A common task when writing your own Rails applications using ActiveRecord is creating your own valid]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>A common task when writing your own Rails applications using ActiveRecord is creating your own validations for your models. While it’s perfectly correct to add the validation directly into the model you’re going to need it, sometimes you’d like to reuse the same validation logic  in other models and we’re not really going to do a cut-and-paste here are we?</p>
<p>The simplest solution when you’re validating fields (and not the whole model) is to use the validates_each method, as it has some nice features seen in other validations that might interest you as the :if, :unless, :allow_blank and :allow_nil options.</p>
<p>Our custom example validation is to validate that one or more fields are different from one specific field. Imagine that you’re building an invoices application, having the seller to also be the buyer isn’t really what you’re looking for, so that’s why we’re building this validation. Let’s take a look at the validation code:</p>
<pre class="brush: ruby;">ActiveRecord::Base.class_eval do

  def self.validates_different( *args )

    options = args.extract_options!
    raise &#34;You must define a :field option to compare to&#34; if options[:field].blank?

    validates_each(*(args &#60;&#60; options)) do &#124;record, attribute, value&#124;
      if record.send( options[:field] ) == value
        record.errors.add(
          attribute,
          record.errors.generate_message(
            attribute
            'different',
            :field =&#62; record.class.human_attribute_name( options[:field].to_s ) ) )
      end
      true
    end

  end

end</pre>
<p>We have inserted a static method inside the ActiveRecord::Base class to be our validation macro, it takes a list of parameters and an options hash at the end, here’s a sample of how it would be used:</p>
<pre class="brush: ruby;">class Invoice &#60; ActiveRecord::Base
    validates_different :seller_id, :field =&#62; :buyer_id, :allow_blank =&#62; true
end</pre>
<p>The validation looks just like any other ActiveRecord validation and even uses options well known in them like :allow_blank, keeping the principle of least surprise at bay. It’s also important to notice the use of I18N on the validation message, the “&#8217;activerecord.errors.messages” namespace is the ActiveRecord error messages namespace and that’s where you should add your custom validation messages, do not place the messages directly inside your validation or model code. Here’s how the YAML file would look like:</p>
<pre class="brush: plain;">en:
  activerecord:
    errors:
      messages:
        different: “must be different than {{field}}”</pre>
<p>And there you go, you have built your own validation macro for your ActiveRecord models and even used the I18N helpers to keep the messages away from your model code.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Τι είναι το ActiveRecord?]]></title>
<link>http://dotnetdelver.wordpress.com/2009/09/07/%cf%84%ce%b9-%ce%b5%ce%af%ce%bd%ce%b1%ce%b9-%cf%84%ce%bf-activerecord/</link>
<pubDate>Mon, 07 Sep 2009 19:55:14 +0000</pubDate>
<dc:creator>dotnetdelver</dc:creator>
<guid>http://dotnetdelver.wordpress.com/2009/09/07/%cf%84%ce%b9-%ce%b5%ce%af%ce%bd%ce%b1%ce%b9-%cf%84%ce%bf-activerecord/</guid>
<description><![CDATA[Το ActiveRecord από την ομάδα του CastleProject είναι βασισμένο στο σχεδιαστικό πρότυπο(ποιός τις σκ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Το ActiveRecord από την ομάδα του <a href="http://www.castleproject.org/activerecord/index.html" target="_blank">CastleProject</a> είναι βασισμένο στο σχεδιαστικό πρότυπο(ποιός τις σκέφτεται αυτές τις μεταφράσεις αναρωτιέμαι) του <a href="http://en.wikipedia.org/wiki/Active_record_pattern" target="_blank">active record</a>. Στην ουσία δρα ως ένας μεσάζωντας μεταξύ της εφαρμογής και της βάσης δεδομένων.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Double Shot #523]]></title>
<link>http://afreshcup.com/2009/08/21/double-shot-523/</link>
<pubDate>Fri, 21 Aug 2009 08:22:30 +0000</pubDate>
<dc:creator>Mike Gunderloy</dc:creator>
<guid>http://afreshcup.com/2009/08/21/double-shot-523/</guid>
<description><![CDATA[There&#8217;s early and then there&#8217;s insanely early. master_slave_adapter &#8211; Nice approac]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>There&#8217;s early and then there&#8217;s insanely early.</p>
<ul>
<li><strong><a href="http://github.com/mauricio/master_slave_adapter/tree/master">master_slave_adapter</a></strong> &#8211; Nice approach to doing master-slave databases in Active Record through a custom adapter that dispatches the database calls.</li>
<li><strong><a href="http://lachlankeown.blogspot.com/2008/05/online-viewstate-viewer-decoder.html">Online Viewstate Viewer / Decoder for Asp.Net 2.0</a></strong> &#8211; I didn&#8217;t think I&#8217;d need this sort of thing any more. I was wrong.</li>
<li><strong><a href="http://github.com/oggy/looksee/tree/master">looksee</a></strong> &#8211; Library to examine the method lookup path of ruby objects.</li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[before_destroy and :dependent =&gt; :destroy]]></title>
<link>http://gaimuk.wordpress.com/2009/08/12/before_destroy-and-dependent-destroy/</link>
<pubDate>Wed, 12 Aug 2009 10:03:33 +0000</pubDate>
<dc:creator>gaimuk</dc:creator>
<guid>http://gaimuk.wordpress.com/2009/08/12/before_destroy-and-dependent-destroy/</guid>
<description><![CDATA[Consider the following model class Activity has_many :tags, :dependent =&gt; :destroy before_destroy]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Consider the following model</p>
<pre>class Activity
  has_many :tags, :dependent =&#62; :destroy
  before_destroy :do_something

  def do_something
    # do something
  end
end</pre>
<p>When calling @activity.destroy, the order of execution is</p>
<ol>
<li>Destroy @activity.tags</li>
<li>do_something</li>
<li>Destroy @activity</li>
</ol>
<p>Before_destroy is executed after the destroy of it&#8217;s association.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Maven, JRuby and Rails Migrations]]></title>
<link>http://cdivilly.wordpress.com/2009/07/20/maven-jruby-and-rails-migrations/</link>
<pubDate>Mon, 20 Jul 2009 15:19:44 +0000</pubDate>
<dc:creator>cdivilly</dc:creator>
<guid>http://cdivilly.wordpress.com/2009/07/20/maven-jruby-and-rails-migrations/</guid>
<description><![CDATA[Here&#8217;s how I managed to get Rails Migrations working with a Maven build process, enabling me t]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Here&#8217;s how I managed to get Rails Migrations working with a Maven build process, enabling me to leverage Migrations to maintain the RDBMS schema of a Java application.</p>
<h3>Add JRuby and Database dependencies</h3>
<p>Add the following dependencies to your pom.xml (adjust for whatever is latest version of jruby and whatever your database is).</p>
<pre>  &#60;dependency&#62;
   &#60;groupId&#62;org.jruby&#60;/groupId&#62;
   &#60;artifactId&#62;jruby-complete&#60;/artifactId&#62;
   &#60;version&#62;1.3.0RC1&#60;/version&#62;
  &#60;/dependency&#62;
  &#60;dependency&#62;
   &#60;groupId&#62;oracle&#60;/groupId&#62;
   &#60;artifactId&#62;jdbc&#60;/artifactId&#62;
   &#60;version&#62;11.1.0&#60;/version&#62;
  &#60;/dependency&#62;</pre>
<h3>Add a goal to install required Ruby gems</h3>
<p>To get Rails migrations running we&#8217;ll need the following gems:</p>
<ul>
<li>activerecord</li>
<li>activerecord-jdbc-adapter</li>
<li>your <em>database specific</em> jdbc adapter</li>
</ul>
<p>We&#8217;ll set up a profile to install these gems if they are missing (based on a approach used by <a title="Maven, JRuby, Cucumber" href="http://binil.wordpress.com/2008/10/29/running-cucumber-on-jrubymaven/">Binil Thomas</a>):</p>
<pre>&#60;profiles&#62;
  &#60;profile&#62;
   &#60;id&#62;first.time&#60;/id&#62;
   &#60;activation&#62;
    &#60;file&#62;
     &#60;missing&#62;${user.home}/.gem/jruby/1.8/gems/activerecord-2.3.2&#60;/missing&#62;
    &#60;/file&#62;
   &#60;/activation&#62;
   &#60;build&#62;
    &#60;plugins&#62;
     &#60;plugin&#62;
      &#60;groupId&#62;org.codehaus.mojo&#60;/groupId&#62;
      &#60;artifactId&#62;exec-maven-plugin&#60;/artifactId&#62;
      &#60;executions&#62;
       &#60;execution&#62;
        &#60;id&#62;install-active-record-gem&#60;/id&#62;
        &#60;phase&#62;initialize&#60;/phase&#62;
        &#60;goals&#62;
         &#60;goal&#62;java&#60;/goal&#62;
        &#60;/goals&#62;
        &#60;configuration&#62;
         &#60;mainClass&#62;org.jruby.Main&#60;/mainClass&#62;
         &#60;arguments&#62;
          &#60;argument&#62;-S&#60;/argument&#62;
          &#60;argument&#62;gem&#60;/argument&#62;
          &#60;argument&#62;install&#60;/argument&#62;
          &#60;argument&#62;activerecord&#60;/argument&#62;
          &#60;argument&#62;activerecord-jdbc-adapter&#60;/argument&#62;
          &#60;argument&#62;activerecord-oracle_enhanced-adapter&#60;/argument&#62;
          &#60;argument&#62;--no-ri&#60;/argument&#62;
          &#60;argument&#62;--no-rdoc&#60;/argument&#62;
          &#60;argument&#62;--no-test&#60;/argument&#62;
         &#60;/arguments&#62;
        &#60;/configuration&#62;
       &#60;/execution&#62;
      &#60;/executions&#62;
     &#60;/plugin&#62;
    &#60;/plugins&#62;
   &#60;/build&#62;
  &#60;/profile&#62;
 &#60;/profiles&#62;</pre>
<p>Replace <code>activerecord-oracle_enhanced-adapter</code> with the name of your chosen database&#8217;s jdbc adapter.</p>
<h3>Add a goal to run the migration</h3>
<pre> &#60;build&#62;
  &#60;plugins&#62;
   &#60;plugin&#62;
    &#60;groupId&#62;org.codehaus.mojo&#60;/groupId&#62;
    &#60;artifactId&#62;exec-maven-plugin&#60;/artifactId&#62;
    &#60;executions&#62;
     &#60;execution&#62;
      &#60;id&#62;run-migrate&#60;/id&#62;
      &#60;phase&#62;install&#60;/phase&#62;
      &#60;goals&#62;
       &#60;goal&#62;java&#60;/goal&#62;
      &#60;/goals&#62;
      &#60;configuration&#62;
       &#60;mainClass&#62;org.jruby.Main&#60;/mainClass&#62;
       &#60;arguments&#62;
        &#60;argument&#62;-S&#60;/argument&#62;
        &#60;argument&#62;rake&#60;/argument&#62;
        &#60;argument&#62;-f&#60;/argument&#62;
        &#60;argument&#62;${basedir}/Rakefile&#60;/argument&#62;
       &#60;/arguments&#62;
      &#60;/configuration&#62;
     &#60;/execution&#62;
    &#60;/executions&#62;
   &#60;/plugin&#62;
  &#60;/plugins&#62;
 &#60;/build&#62;</pre>
<h3>Create a Rakefile</h3>
<p>You&#8217;ll need a Rakefile to carry out the migration, in my case I wanted to avoid depending on all of Rails so I just used the following:</p>
<pre>require 'active_record'
require 'yaml'

RAILS_ROOT = "#{File.dirname(__FILE__)}" unless defined?(RAILS_ROOT)

task :default =&#62; :migrate

task :migrate =&#62; :environment do
  ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil )
end

task :environment do
  ActiveRecord::Base.establish_connection(YAML::load(File.open("#{RAILS_ROOT}/config/database.yml")))
  ActiveRecord::Base.logger = Logger.new(File.open('database.log', 'a'))
end</pre>
<h3>Write your migrations</h3>
<p>Create your <a href="http://api.rubyonrails.org/classes/ActiveRecord/Migration.html">migrations</a> in <code>db/migrate</code>.</p>
<h3>Apply database changes</h3>
<p>Finally type:</p>
<pre>mvn install</pre>
<p>to deploy your database changes.</p>
<h3>The full POM</h3>
<pre>
&#60;project&#62;
 &#60;modelVersion&#62;4.0.0&#60;/modelVersion&#62;
 &#60;groupId&#62;org.example&#60;/groupId&#62;
 &#60;artifactId&#62;schema&#60;/artifactId&#62;
 &#60;name&#62;Example POM for doing Rails Migrations&#60;/name&#62;
 &#60;packaging&#62;pom&#60;/packaging&#62;
 &#60;dependencies&#62;
  &#60;dependency&#62;
   &#60;groupId&#62;org.jruby&#60;/groupId&#62;
   &#60;artifactId&#62;jruby-complete&#60;/artifactId&#62;
   &#60;version&#62;1.3.0RC1&#60;/version&#62;
  &#60;/dependency&#62;
  &#60;dependency&#62;
   &#60;groupId&#62;oracle&#60;/groupId&#62;
   &#60;artifactId&#62;jdbc&#60;/artifactId&#62;
   &#60;version&#62;11.2.0&#60;/version&#62;
  &#60;/dependency&#62;
 &#60;/dependencies&#62;
 &#60;build&#62;
  &#60;plugins&#62;
   &#60;plugin&#62;
    &#60;groupId&#62;org.codehaus.mojo&#60;/groupId&#62;
    &#60;artifactId&#62;exec-maven-plugin&#60;/artifactId&#62;
    &#60;executions&#62;
     &#60;execution&#62;
      &#60;id&#62;run-migrate&#60;/id&#62;
      &#60;phase&#62;install&#60;/phase&#62;
      &#60;goals&#62;
       &#60;goal&#62;java&#60;/goal&#62;
      &#60;/goals&#62;
      &#60;configuration&#62;
       &#60;mainClass&#62;org.jruby.Main&#60;/mainClass&#62;
       &#60;arguments&#62;
        &#60;argument&#62;-S&#60;/argument&#62;
        &#60;argument&#62;rake&#60;/argument&#62;
        &#60;argument&#62;-f&#60;/argument&#62;
        &#60;argument&#62;${basedir}/Rakefile&#60;/argument&#62;
       &#60;/arguments&#62;
      &#60;/configuration&#62;
     &#60;/execution&#62;
    &#60;/executions&#62;
   &#60;/plugin&#62;
  &#60;/plugins&#62;
 &#60;/build&#62;
 &#60;profiles&#62;
  &#60;profile&#62;
   &#60;id&#62;first.time&#60;/id&#62;
   &#60;activation&#62;
    &#60;file&#62;
     &#60;missing&#62;${user.home}/.gem/jruby/1.8/gems/activerecord-2.3.2&#60;/missing&#62;
    &#60;/file&#62;
   &#60;/activation&#62;
   &#60;build&#62;
    &#60;plugins&#62;
     &#60;plugin&#62;
      &#60;groupId&#62;org.codehaus.mojo&#60;/groupId&#62;
      &#60;artifactId&#62;exec-maven-plugin&#60;/artifactId&#62;
      &#60;executions&#62;
       &#60;execution&#62;
        &#60;id&#62;install-active-record-gem&#60;/id&#62;
        &#60;phase&#62;initialize&#60;/phase&#62;
        &#60;goals&#62;
         &#60;goal&#62;java&#60;/goal&#62;
        &#60;/goals&#62;
        &#60;configuration&#62;
         &#60;mainClass&#62;org.jruby.Main&#60;/mainClass&#62;
         &#60;arguments&#62;
          &#60;argument&#62;-S&#60;/argument&#62;
          &#60;argument&#62;gem&#60;/argument&#62;
          &#60;argument&#62;install&#60;/argument&#62;
          &#60;argument&#62;activerecord&#60;/argument&#62;
          &#60;argument&#62;activerecord-jdbc-adapter&#60;/argument&#62;
          &#60;argument&#62;activerecord-oracle_enhanced-adapter&#60;/argument&#62;
          &#60;argument&#62;--no-ri&#60;/argument&#62;
          &#60;argument&#62;--no-rdoc&#60;/argument&#62;
          &#60;argument&#62;--no-test&#60;/argument&#62;
         &#60;/arguments&#62;
        &#60;/configuration&#62;
       &#60;/execution&#62;
      &#60;/executions&#62;
     &#60;/plugin&#62;
    &#60;/plugins&#62;
   &#60;/build&#62;
  &#60;/profile&#62;
 &#60;/profiles&#62;
&#60;/project&#62;
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Ruby on Rails interview questions - part 2]]></title>
<link>http://vladzloteanu.wordpress.com/2009/06/30/ruby-on-rails-interview-questions-part-2/</link>
<pubDate>Tue, 30 Jun 2009 17:25:25 +0000</pubDate>
<dc:creator>vladzloteanu</dc:creator>
<guid>http://vladzloteanu.wordpress.com/2009/06/30/ruby-on-rails-interview-questions-part-2/</guid>
<description><![CDATA[Continuing the &#8220;RoR interview questions&#8221; sequel(part one here) , these are some general ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Continuing the &#8220;RoR interview questions&#8221; sequel(<a href="http://vladzloteanu.wordpress.com/2009/06/15/ruby-on-rails-interview-questions/" target="_blank">part one here</a>) , these are some general Rails concepts and technologies questions. Enjoy <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p><!--more--></p>
<p><strong>Why RoR?</strong></p>
<p>0)for fast developing websites<br />
1) DRY<br />
2)convention over configuration<br />
3)scaffolding<br />
4)pure Object oriented concepts<br />
5)less coding<br />
6)easy understanding of coding<br />
7)follows MVC architecture<br />
8)using library and gem files</p>
<p>(from: http://www.rubyassist.com/rubyonrailsinterviewquestions)</p>
<p><strong>What is agile development? What are the strenghts?</strong></p>
<p><strong>Agile software development</strong> refers to a group of <a title="Software development methodologies" href="http://en.wikipedia.org/wiki/Software_development_methodologies">software development methodologies</a> based on iterative development, where requirements and solutions evolve through collaboration between self-organizing cross-functional teams</p>
<p>Advantages:</p>
<ul>
<li>Customer satisfaction by rapid, continuous delivery of useful software</li>
<li>Working software is delivered frequently (weeks rather than months)</li>
<li>Projects are built around motivated individuals, who should be trusted</li>
<li>Continuous attention to technical excellence and good design</li>
<li>Simplicity</li>
<li>Self-organizing teams</li>
<li>Regular adaptation to changing circumstances</li>
</ul>
<p><strong>What is MVC? Explain each element.</strong></p>
<p><strong>Name some of the the new features that Rails 2.0, 2.1, 2.3 brings.</strong></p>
<p><strong><br />
</strong></p>
<h3>Model Questions</h3>
<p><strong>What can you define in model?</strong></p>
<p>1. Validations (like validates_presence_of, numeracility_of, format_of etc.)<br />
2. Relationships(like has_one, has_many, HABTM etc.)<br />
3. Callbacks(like before_save, after_save, before_create etc.)<br />
4. Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model<br />
5. ROR Queries in Sql</p>
<p>(answer from: http://railsbuilder.blogspot.com/2009/04/ruby-on-rails-interview-questions.html)</p>
<p><strong>What is ActiveRecord? What is ORM?</strong></p>
<p><strong>Model relationships</strong></p>
<ul>
<li><tt>belongs_to</tt></li>
<li><tt>has_one</tt></li>
<li><tt>has_many</tt></li>
<li><tt>has_many :through</tt></li>
</ul>
<p>A <tt>has_many :through</tt> association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding <em>through</em> a third model</p>
<ul>
<li><tt>has_one :through</tt></li>
<li><tt>has_and_belongs_to_many</tt></li>
</ul>
<p><strong>What is the difference between has_one and belongs_to?</strong></p>
<p>The distinction is in where you place the foreign key (it goes on the table for the class declaring the <tt>belongs_to</tt> association), but you should give some thought to the actual meaning of the data as well. The <tt>has_one</tt> relationship says that one of something is yours – that is, that something points back to you. For example, it makes more sense to say that a supplier owns an account than that an account owns a supplie</p>
<p><strong>Model Validations</strong></p>
<p><strong>What is validates_associated?</strong></p>
<p>Validates whether the associated object or objects are all valid themselves. Works with any kind of association.</p>
<p><strong>Model callbacks</strong></p>
<p><a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html">Callbacks</a> are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when <tt>destroy</tt> is called (by overwriting <tt><a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002441">before_destroy</a></tt>) or to massage attributes before they‘re validated (by overwriting <tt><a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002435">before_validation</a></tt>)</p>
<p><strong>What is the difference between <em>save</em> and <em>save!</em> ?</strong></p>
<p>Save! performs all validations and callbacks. If any validation returns false, save! throws an error and canceles the save.<br />
Save does not throw any error in the case above, but canceles the save. Also, the validators can be bypassed.</p>
<p><strong>Related objects newly created. When are they saved?</strong></p>
<p>When you assign an object to a <tt>has_many</tt> association, that object is automatically saved (in order to update its foreign key). If you assign multiple objects in one statement, then they are all saved.</p>
<p>If any of these saves fails due to validation errors, then the assignment statement returns <tt>false</tt> and the assignment itself is cancelled.</p>
<p>If the parent object (the one declaring the <tt>has_many</tt> association) is unsaved (that is, <tt>new_record?</tt> returns <tt>true</tt>) then the child objects are not saved when they are added. All unsaved members of the association will automatically be saved when the parent is saved.</p>
<p>If you want to assign an object to a <tt>has_many</tt> association without saving the object, use the <tt><em>collection</em>.build</tt> method.</p>
<p><strong>Model relationships? How is &#8220;has_and_belongs_to_many&#8221; implemented in the database?</strong></p>
<p>A. Polymorphic associations</p>
<p><code>belongs_to<span> :imageable</span>,<span> :polymorphic</span> =&#62; true </code></p>
<p><code>has_many<span> :pictures</span>,<span> :as</span> =&#62;<span> :imageable</span></code></p>
<p><code>has_many<span> :pictures</span>,<span> :as</span> =&#62;<span> :imageable</span></code></p>
<p><span>B. Self joins</span></p>
<p><strong><span>What is the difference between delete and destroy?</span></strong></p>
<p><span>Delete removes the association, destroy removes also the associated record from the DB.<br />
</span></p>
<h3>Controllers</h3>
<p><strong>What are the types of routes that can be declared in routes.rb?</strong></p>
<p><strong>What are REST routes?</strong></p>
<p>CRUD rest routes (for <code>map.resources<span> :photos</span></code>):</p>
<table border="0">
<tbody>
<tr>
<th><span>HTTP</span> vb</th>
<th><span>URL</span></th>
<th>controller</th>
<th>action</th>
<th>used for</th>
</tr>
<tr>
<td><span>GET</span></td>
<td>/photos</td>
<td>Photos</td>
<td>index</td>
<td>display a list of all photos</td>
</tr>
<tr>
<td><span>GET</span></td>
<td>/photos/new</td>
<td>Photos</td>
<td>new</td>
<td>return an <span>HTML</span> form for creating a new photo</td>
</tr>
<tr>
<td><span>POST</span></td>
<td>/photos</td>
<td>Photos</td>
<td>create</td>
<td>create a new photo</td>
</tr>
<tr>
<td><span>GET</span></td>
<td>/photos/1</td>
<td>Photos</td>
<td>show</td>
<td>display a specific photo</td>
</tr>
<tr>
<td><span>GET</span></td>
<td>/photos/1/edit</td>
<td>Photos</td>
<td>edit</td>
<td>return an <span>HTML</span> form for editing a photo</td>
</tr>
<tr>
<td><span>PUT</span></td>
<td>/photos/1</td>
<td>Photos</td>
<td>update</td>
<td>update a specific photo</td>
</tr>
<tr>
<td><span>DELETE</span></td>
<td>/photos/1</td>
<td>Photos</td>
<td>destroy</td>
<td>delete a specific photo</td>
</tr>
</tbody>
</table>
<p><strong>What is the difference between photos_url and photos_path?</strong></p>
<p><code>photos_url  <span># =&#62; "http://www.example.com/photos"</span> </code></p>
<p><code>photos_path <span># =&#62; "/photos"</span> </code></p>
<p><strong>What are filters? and how many types of filters are there  in ruby?</strong></p>
<p>Filters are methods that are run before, after or “around” a controller action.</p>
<p>Filters are inherited, so if you set a filter on <tt>ApplicationController</tt>, it will be run on every controller in your application.</p>
<p>Filter can take one of three forms: method reference (symbol), external class, or inline method (proc).</p>
<ul>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000551">after_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000549">append_after_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000552">append_around_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000546">append_before_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000554">around_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000548">before_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000558">filter_chain</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000550">prepend_after_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000553">prepend_around_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000547">prepend_before_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000556">skip_after_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000555">skip_before_filter</a></li>
<li><a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000557">skip_filter</a></li>
</ul>
<p><strong>What is the flash?</strong></p>
<p>The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash.</p>
<p><strong>What is the h function? Against what kinds of attacks can it help?</strong></p>
<h3>Helpers</h3>
<p><strong>What are helpers? What can you put in a helper?</strong></p>
<p><strong>From where can the methods in a helper be accessed?<br />
</strong></p>
<h3>View</h3>
<h4>How are the errors displayed in the view?</h4>
<h4><tt>error_messages</tt> and <tt>error_messages_for</tt></h4>
<p><strong>Difference between form_for and form_tag</strong></p>
<p><strong>What is a .rjs file? Why do we use request.xhr? in rails</strong></p>
<p><strong>What is REST?</strong></p>
<p><strong>Rails caching strategies</strong></p>
<p><strong>Rails cache sweepers</strong></p>
<p>Sweepers are the terminators of the caching world and responsible for expiring caches when model objects change. They do this by being half-observers, half-filters and implementing callbacks for both roles.</p>
<h3>Plugins</h3>
<p><strong>What are Rails plugins? Give example (comment) on some plugins you have used.</strong></p>
<h3><strong>Rails Middleware</strong></h3>
<p><strong>What is Rails Rack?</strong></p>
<p><strong>What is Rails Metal?<br />
</strong></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[count v.s. lenght v.s. size]]></title>
<link>http://ericzouthoughts.wordpress.com/2009/06/20/count-v-s-lenght-v-s-size/</link>
<pubDate>Sat, 20 Jun 2009 17:24:04 +0000</pubDate>
<dc:creator>ericzou</dc:creator>
<guid>http://ericzouthoughts.wordpress.com/2009/06/20/count-v-s-lenght-v-s-size/</guid>
<description><![CDATA[there are couple difference between count and length, generally speaking, count does&#8217;t load th]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>there are couple difference between count and length, generally speaking, count does&#8217;t load the array so it is faster. However, there are situation count won&#8217;t give you an accurate number<br />
here is an example</p>
<p>suppose you have three tables &#8216;users&#8217;, &#8216;roles&#8217;, and the join table &#8216;roles_users&#8217;, and you want to all active users that has role of &#8216;user&#8217; or &#8216;admin&#8217;<br />
Here is how to get it in rails:</p>
<pre style='color:#d1d1d1;background:#000000;'>named_scope :active, :joins<span style='color:#d2cd86;'>=</span>&#62; :roles,
     :conditions<span style='color:#d2cd86;'>=</span>&#62;<span style='color:#d2cd86;'>[</span><span style='color:#00c4c4;'>'state=? and roles.name in (?) '</span>, <span style='color:#00c4c4;'>'active'</span>, <span style='color:#d2cd86;'>[</span><span style='color:#00c4c4;'>'user'</span>, <span style='color:#00c4c4;'>'admin'</span><span style='color:#d2cd86;'>]</span> <span style='color:#d2cd86;'>]</span>, :group<span style='color:#d2cd86;'>=</span>&#62;<span style='color:#00c4c4;'>'id'</span>
</pre>
<p>here group is necessary otherwise you will get duplicate users records if users has more than one role.</p>
<p>Here is where length different than count:<br />
say joe is the only user and he has both user and admin roles</p>
<pre style='color:#d1d1d1;background:#000000;'>User<span style='color:#d2cd86;'>.</span>active<span style='color:#d2cd86;'>.</span>count <span style='color:#9999a9;'># returns 2</span>
User<span style='color:#d2cd86;'>.</span>active<span style='color:#d2cd86;'>.</span>length <span style='color:#9999a9;'># returns 1</span>
</pre>
<p>It is easy to figure out why through SQL:<br />
the named_scope translate to </p>
<pre style='color:#d1d1d1;background:#000000;'><span style='color:#e66170;font-weight:bold;'>select</span> u<span style='color:#d2cd86;'>.</span>id, u<span style='color:#d2cd86;'>.</span>first_name, u<span style='color:#d2cd86;'>.</span>email
from users u
inner join roles_users ru on ru<span style='color:#d2cd86;'>.</span>user_id <span style='color:#d2cd86;'>=</span> u<span style='color:#d2cd86;'>.</span>id
inner join roles r on r<span style='color:#d2cd86;'>.</span>id <span style='color:#d2cd86;'>=</span> ru<span style='color:#d2cd86;'>.</span>role_id
where u<span style='color:#d2cd86;'>.</span>state <span style='color:#d2cd86;'>=</span> <span style='color:#00c4c4;'>'active'</span> <span style='color:#e66170;font-weight:bold;'>and</span> r<span style='color:#d2cd86;'>.</span>name <span style='color:#e66170;font-weight:bold;'>in</span> <span style='color:#d2cd86;'>(</span><span style='color:#00c4c4;'>'user'</span>, <span style='color:#00c4c4;'>'admin'</span><span style='color:#d2cd86;'>)</span>
group by u<span style='color:#d2cd86;'>.</span>id;
</pre>
<p>the count translates to </p>
<pre style='color:#d1d1d1;background:#000000;'><span style='color:#e66170;font-weight:bold;'>select</span> count<span style='color:#d2cd86;'>(</span><span style='color:#d2cd86;'>*</span><span style='color:#d2cd86;'>)</span>, u<span style='color:#d2cd86;'>.</span>id, u<span style='color:#d2cd86;'>.</span>first_name, u<span style='color:#d2cd86;'>.</span>email
from users u
inner join roles_users ru on ru<span style='color:#d2cd86;'>.</span>user_id <span style='color:#d2cd86;'>=</span> u<span style='color:#d2cd86;'>.</span>id
inner join roles r on r<span style='color:#d2cd86;'>.</span>id <span style='color:#d2cd86;'>=</span> ru<span style='color:#d2cd86;'>.</span>role_id
where u<span style='color:#d2cd86;'>.</span>id <span style='color:#d2cd86;'>=</span> <span style='color:#008c00;'>2</span> <span style='color:#e66170;font-weight:bold;'>and</span> r<span style='color:#d2cd86;'>.</span>name <span style='color:#e66170;font-weight:bold;'>in</span> <span style='color:#d2cd86;'>(</span><span style='color:#00c4c4;'>'user'</span>, <span style='color:#00c4c4;'>'admin'</span><span style='color:#d2cd86;'>)</span>
group by u<span style='color:#d2cd86;'>.</span>id;
</pre>
<pre style='color:#d1d1d1;background:#000000;'>without group by
<span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span>
&#124; id &#124; first_name &#124; email              &#124;
<span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span>
&#124;  <span style='color:#008c00;'>1</span> &#124; Joe        &#124;    joe@example<span style='color:#d2cd86;'>.</span>com &#124;
&#124;  <span style='color:#008c00;'>1</span> &#124; Joe        &#124;    joe@example<span style='color:#d2cd86;'>.</span>com &#124;
<span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span>
<span style='color:#008c00;'>5</span> rows <span style='color:#e66170;font-weight:bold;'>in</span> set <span style='color:#d2cd86;'>(</span><span style='color:#009f00;'>0.00</span> sec<span style='color:#d2cd86;'>)</span>

with group by
<span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span>
&#124; id &#124; first_name &#124; email              &#124;
<span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span>
&#124;  <span style='color:#008c00;'>1</span> &#124; Joe        &#124;    joe@example<span style='color:#d2cd86;'>.</span>com &#124;
<span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span>
<span style='color:#008c00;'>1</span> row <span style='color:#e66170;font-weight:bold;'>in</span> set <span style='color:#d2cd86;'>(</span><span style='color:#009f00;'>0.00</span> sec<span style='color:#d2cd86;'>)</span>

using count <span style='color:#e66170;font-weight:bold;'>and</span> here is why it returns <span style='color:#008c00;'>2</span>
<span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span>
&#124; count<span style='color:#d2cd86;'>(</span><span style='color:#d2cd86;'>*</span><span style='color:#d2cd86;'>)</span> &#124; id &#124; first_name &#124; email              &#124;
<span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span>
&#124;        <span style='color:#008c00;'>2</span> &#124;  <span style='color:#008c00;'>1</span> &#124; Joe        &#124;    joe@example<span style='color:#d2cd86;'>.</span>com &#124;
<span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>-</span><span style='color:#d2cd86;'>+</span>
<span style='color:#008c00;'>1</span> row <span style='color:#e66170;font-weight:bold;'>in</span> set <span style='color:#d2cd86;'>(</span><span style='color:#009f00;'>0.00</span> sec<span style='color:#d2cd86;'>)</span>
</pre>
<p>the bottom line: don&#8217;t use count when using :group</p>
<p>p.s. for more difference between length, size and count, read this blog post: http://rhnh.net/2007/09/26/counting-activerecord-associations-count-size-or-length</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[My aproach for doing "DDD on Ruby" - Introduction and Part I]]></title>
<link>http://dddonruby.wordpress.com/2009/06/08/my-aproach-for-doing-ddd-on-ruby-introduction-and-part-i/</link>
<pubDate>Mon, 08 Jun 2009 04:29:47 +0000</pubDate>
<dc:creator>Fábio Rehm</dc:creator>
<guid>http://dddonruby.wordpress.com/2009/06/08/my-aproach-for-doing-ddd-on-ruby-introduction-and-part-i/</guid>
<description><![CDATA[Introduction We all know that in Domain-Driven Design it is good to express our domain with simplici]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><h2>Introduction</h2>
<p>We all know that in Domain-Driven Design it is good to express our domain with simplicity and &#8220;pureness&#8221; and for that we usually go for a POxO (Plain Old <em>{fill_with_your_preffered_language}</em> Object) approach. The problem is that the ORM solutions I&#8217;ve found for Ruby make us either inherit from some base class or do the mappings directly into our classes. By no means am I saying that they aren&#8217;t good, but we are talking about DDD and the idea of having a pure domain layer without distractions is something we should embrace.</p>
<p>My first thought was to write about a full blown example, comparing side by side a common C# / Java implementations to my Ruby implementation but then I realized it would probably have some unnecessary and &#8220;boring&#8221; information. It&#8217;s better to focus on writing about my approach and have some comments here and there to explain how things would be done in other platforms. What I&#8217;m going to show here is something that is really common in other languages but not in Ruby I believe, all classes from my domain will be implemented as POROs &#8211; Plain Old Ruby Objects, totaly decoupled from any tool that we might use.</p>
<p>There was a talk by Eric Evans called <a href="http://domaindrivendesign.org/node/80" target="_blank">&#8220;What I&#8217;ve learned about DDD since the book&#8221;</a> that has been commented out <a href="http://www.markhneedham.com/blog/2009/03/13/qcon-london-2009-what-ive-learned-about-ddd-since-the-book-eric-evans/" target="_blank">here</a> and <a href="http://gojko.net/2009/03/12/qcon-london-2009-eric-evans-what-ive-learned-about-ddd-since-the-book/" target="_blank">here</a> (<a href="http://qconlondon.com/london-2009/file?path=/qcon-london-2009/slides/EricEvans_WhatIveLearnedAboutDDDSinceTheBook.pdf" target="_blank">slides here</a>). Even though the building blocks of Model-Driven Design mentioned in the book (and the <a href="http://dddsample.sourceforge.net/characterization.html#Domain_Event">other one</a> mentioned on the talk) are not essential, they are important and will be the subject of this series.</p>
<p>So, to illustrate my ideas I&#8217;ll use the common Customer/Order/Product for my examples with some requirements from <a href="http://www.amazon.com/Applying-Domain-Driven-Design-Patterns-Examples/dp/0321268202" target="_blank">Jimmy Nilsson &#8211; Applying Domain-Driven Design and Patterns</a>:</p>
<ul>
<li>List the orders when looking at a specific customer</li>
<li>Orders have an acceptance status that is changed by the user</li>
<li>The total value of an order must be lower or equal than one million US$</li>
<li>A Customer has a credit limit and cannot owe us more than a specified amount of money</li>
</ul>
<h2>Part I &#8211; Customer and Products</h2>
<p>If you are not familiar with DDD and its building blocks I suggest that have a look at this <a href="http://domaindrivendesign.org/resources/ddd_terms" target="_blank">glossary of DDD terms</a>.</p>
<p>This is our really simple model for this part:</p>
<p style="text-align:center;"><img class="size-medium wp-image-104 aligncenter" title="model" src="http://dddonruby.wordpress.com/files/2009/05/exemplo-blog-model-part-1.jpg?w=300" alt="model" width="300" height="148" /></p>
<h2>Entities</h2>
<p>There&#8217;s no big deal here so I&#8217;ll just provide some code:</p>
<pre style="color:#d1d1d1;background:#000000;font-size:12px;"><span style="color:#e66170;font-weight:bold;">class</span> Customer
  attr_reader :id
  attr_accessor :name
  attr_accessor :credit_limit

  <span style="color:#e66170;font-weight:bold;">def</span> initialize<span style="color:#d2cd86;">(</span>name, credit_limit)
    @name <span style="color:#d2cd86;">=</span> name
    @credit_limit <span style="color:#d2cd86;">=</span> credit_limit
  <span style="color:#e66170;font-weight:bold;">end</span>
<span style="color:#e66170;font-weight:bold;">end</span>

<span style="color:#e66170;font-weight:bold;">class</span> Product
  attr_reader :id
  attr_accessor :price
  attr_accessor :description

  <span style="color:#e66170;font-weight:bold;">def</span> initialize<span style="color:#d2cd86;">(</span>price, description<span style="color:#d2cd86;">)</span>
    @price <span style="color:#d2cd86;">=</span> price
    @description <span style="color:#d2cd86;">=</span> description
  <span style="color:#e66170;font-weight:bold;">end</span>
<span style="color:#e66170;font-weight:bold;">end</span></pre>
<h2>Repositories</h2>
<p>Statically typed languages like Java and C# would have an interface in order to decouple our domain from infrastructure but Ruby doesn&#8217;t have interfaces. But still&#8230; I believe that we need some kind of <a href="http://en.wikipedia.org/wiki/Design_by_contract">contract</a> for the repositories and instead of having a class with empty methods I&#8217;ll create in-memory repositories as the <a href="http://www.martinfowler.com/eaaCatalog/repository.html" target="_blank">pattern definition</a>:</p>
<pre style="color:#d1d1d1;background:#000000;font-size:12px;"><span style="color:#e66170;font-weight:bold;">class</span> CustomerRepository
  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>store<span style="color:#d2cd86;">(</span>customer<span style="color:#d2cd86;">)</span>
    customer<span style="color:#d2cd86;">.</span>instance_variable_set<span style="color:#d2cd86;">(</span>:@id, next_id<span style="color:#d2cd86;">)</span> <span style="color:#e66170;font-weight:bold;">if</span> customer<span style="color:#d2cd86;">.</span>id<span style="color:#d2cd86;">.</span><span style="color:#e66170;font-weight:bold;">nil</span>?
    customers<span style="color:#d2cd86;">[</span>customer<span style="color:#d2cd86;">.</span>id<span style="color:#d2cd86;">]</span> <span style="color:#d2cd86;">=</span> customer
  <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>find<span style="color:#d2cd86;">(</span>id<span style="color:#d2cd86;">)</span>
    customers<span style="color:#d2cd86;">[</span>id<span style="color:#d2cd86;">]</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>all
    customers<span style="color:#d2cd86;">.</span>values
  <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>delete<span style="color:#d2cd86;">(</span>customer<span style="color:#d2cd86;">)</span>
    customers<span style="color:#d2cd86;">.</span>delete<span style="color:#d2cd86;">(</span>customer<span style="color:#d2cd86;">.</span>id<span style="color:#d2cd86;">)</span>
  <span style="color:#e66170;font-weight:bold;">end</span>  

  private  

  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>customers
<span style="color:#e66170;font-weight:bold;">    if</span> !<span style="color:#e66170;font-weight:bold;">defined</span>?<span style="color:#d2cd86;">(</span>@@customers<span style="color:#d2cd86;">)</span>
      @@customers <span style="color:#d2cd86;">=</span> <span style="color:#b060b0;">{</span><span style="color:#b060b0;">}</span>
    <span style="color:#e66170;font-weight:bold;">else</span>
      @@customers
    <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>next_id
<span style="color:#e66170;font-weight:bold;">    if</span> !<span style="color:#e66170;font-weight:bold;">defined</span>?<span style="color:#d2cd86;">(</span>@@next_id<span style="color:#d2cd86;">)</span>
      @@next_id <span style="color:#d2cd86;">=</span> <span style="color:#008c00;">1</span>
    <span style="color:#e66170;font-weight:bold;">else</span>
      @@next_id <span style="color:#d2cd86;">+</span><span style="color:#d2cd86;">=</span> <span style="color:#008c00;">1</span>
    <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
<span style="color:#e66170;font-weight:bold;">end</span>

<span style="color:#e66170;font-weight:bold;">class</span> ProductRepository
  <span style="color:#99cc00;"><em><span style="font-weight:bold;"># ... similar code</span></em></span><em> <span style="color:#99cc00;">...</span></em>
<span style="color:#e66170;font-weight:bold;">end</span></pre>
<p>Maybe this code could be factored out somewhere but let&#8217;s just leave as it is for now.</p>
<p>Right now you might be thinking &#8220;This guy is crazy, static methods are evil!!&#8221;. Well, I think that <a href="http://blog.jayfields.com/2007/04/ruby-class-methods.html" target="_blank">it&#8217;s not true</a> when it comes to Ruby class methods. Just below I will show you how we can easily add persistence to our domain.</p>
<p>Even if we want to set up a <a href="http://www.martinfowler.com/articles/injection.html">IoC container</a> I don&#8217;t think it would be a problem since <a href="http://ruby-doc.org/core/classes/Class.html">Ruby classes are objects as well</a>. For example these repositories could be easily injected into a Rails controller instance variable.</p>
<h2>Adding persistence</h2>
<p>If we use (N)Hibernate, we would probably have the mappings file into a different package / assembly, but in Ruby I think it would be enough to just have persistence related code in another file that redefines the classes.</p>
<h3>Mappings</h3>
<pre style="color:#d1d1d1;background:#000000;font-size:12px;"><span style="color:#e66170;font-weight:bold;">class</span> Customer
  include Clipper::Model

  orm<span style="color:#d2cd86;">.</span>map<span style="color:#d2cd86;">(</span><span style="color:#e66170;font-weight:bold;">self</span>, <span style="color:#00c4c4;">"customers"</span><span style="color:#d2cd86;">)</span> <span style="color:#e66170;font-weight:bold;">do</span> &#124;customers&#124;
    customers<span style="color:#d2cd86;">.</span>key<span style="color:#d2cd86;">(</span>customers<span style="color:#d2cd86;">.</span>field<span style="color:#d2cd86;">(</span><span style="color:#00c4c4;">"id"</span>, Clipper::Types::Serial<span style="color:#d2cd86;">)</span><span style="color:#d2cd86;">)</span>
    customers<span style="color:#d2cd86;">.</span>field<span style="color:#d2cd86;">(</span><span style="color:#00c4c4;">"name"</span>, Clipper::Types::<span style="color:#e66170;font-weight:bold;">String</span><span style="color:#d2cd86;">.</span><span style="color:#e66170;font-weight:bold;">new</span><span style="color:#d2cd86;">(</span><span style="color:#008c00;">200</span><span style="color:#d2cd86;">)</span><span style="color:#d2cd86;">)</span>
    customers<span style="color:#d2cd86;">.</span>field<span style="color:#d2cd86;">(</span><span style="color:#00c4c4;">"credit_limit"</span>, Clipper::Types::<span style="color:#e66170;font-weight:bold;">Float</span><span style="color:#d2cd86;">(</span><span style="color:#008c00;">8</span>, <span style="color:#008c00;">2</span><span style="color:#d2cd86;">)</span><span style="color:#d2cd86;">)</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
<span style="color:#e66170;font-weight:bold;">end</span>

<span style="color:#e66170;font-weight:bold;">class</span> Product
  include Clipper::Model

  orm<span style="color:#d2cd86;">.</span>map<span style="color:#d2cd86;">(</span><span style="color:#e66170;font-weight:bold;">self</span>, <span style="color:#00c4c4;">"products"</span><span style="color:#d2cd86;">)</span> <span style="color:#e66170;font-weight:bold;">do</span> &#124;products&#124;
    products<span style="color:#d2cd86;">.</span>key<span style="color:#d2cd86;">(</span>products<span style="color:#d2cd86;">.</span>field<span style="color:#d2cd86;">(</span><span style="color:#00c4c4;">"id"</span>, Clipper::Types::Serial<span style="color:#d2cd86;">)</span><span style="color:#d2cd86;">)</span>
    products<span style="color:#d2cd86;">.</span>field<span style="color:#d2cd86;">(</span><span style="color:#00c4c4;">"description"</span>, Clipper::Types::<span style="color:#e66170;font-weight:bold;">String</span><span style="color:#d2cd86;">.</span><span style="color:#e66170;font-weight:bold;">new</span><span style="color:#d2cd86;">(</span><span style="color:#008c00;">200</span><span style="color:#d2cd86;">)</span><span style="color:#d2cd86;">)</span>
    products<span style="color:#d2cd86;">.</span>field<span style="color:#d2cd86;">(</span><span style="color:#00c4c4;">"price"</span>, Clipper::Types::<span style="color:#e66170;font-weight:bold;">Float</span><span style="color:#d2cd86;">(</span><span style="color:#008c00;">8</span>, <span style="color:#008c00;">2</span><span style="color:#d2cd86;">)</span><span style="color:#d2cd86;">)</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
<span style="color:#e66170;font-weight:bold;">end</span></pre>
<h3>Repositories</h3>
<pre style="color:#d1d1d1;background:#000000;font-size:12px;"><span style="color:#e66170;font-weight:bold;">module</span> ClipperRepository
  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>included<span style="color:#d2cd86;">(</span>klass<span style="color:#d2cd86;">)</span>
    klass<span style="color:#d2cd86;">.</span>instance_eval <span style="color:#e66170;font-weight:bold;">do</span>
      include Singleton
      include Clipper::Session::Helper

      <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>orm
        instance<span style="color:#d2cd86;">.</span>orm
      <span style="color:#e66170;font-weight:bold;">end</span>
    <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
<span style="color:#e66170;font-weight:bold;">end</span>

<span style="color:#e66170;font-weight:bold;">class</span> CustomerRepository
  include ClipperRepository

  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>store<span style="color:#d2cd86;">(</span>customer<span style="color:#d2cd86;">)</span>
    orm<span style="color:#d2cd86;">.</span>save<span style="color:#d2cd86;">(</span>customer<span style="color:#d2cd86;">)</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>delete<span style="color:#d2cd86;">(</span>customer<span style="color:#d2cd86;">)</span>
    orm<span style="color:#d2cd86;">.</span>delete<span style="color:#d2cd86;">(</span>customer<span style="color:#d2cd86;">)</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>find<span style="color:#d2cd86;">(</span>id<span style="color:#d2cd86;">)</span>
    orm<span style="color:#d2cd86;">.</span>get<span style="color:#d2cd86;">(</span>Customer, id<span style="color:#d2cd86;">)</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#e66170;font-weight:bold;">def</span> self<span style="color:#d2cd86;">.</span>all
    orm<span style="color:#d2cd86;">.</span>all<span style="color:#d2cd86;">(</span>Customer<span style="color:#d2cd86;">)</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
<span style="color:#e66170;font-weight:bold;">end</span>

<span style="color:#e66170;font-weight:bold;">class</span> ProductRepository
  <span style="color:#99cc00;"><em><span style="font-weight:bold;"># ... similar cod</span><span style="font-weight:bold;"><span style="color:#99cc00;">e</span></span></em></span><em> </em><span style="color:#e66170;font-weight:bold;"><em><span style="color:#99cc00;"> ...</span></em>
end</span></pre>
<p>Here I&#8217;ve used <a href="http://github.com/wiecklabs/clipper/tree/master" target="_blank">Clipper </a>but for these examples we could probably rewrite it to use <a href="http://datamapper.org/">DataMapper</a> as well. Unfortunately, with this approach both DataMapper and Clipper will redefine our already defined accessors and that would be a problem if we have some business logic there. For this example this wouldn&#8217;t be a problem but I&#8217;ve checked with one of Clipper developers and they are willing to have this feature implemented in the library, I&#8217;ll have to check if DataMapper folks have something like this in mind as well. I&#8217;ve already hacked Clipper in order to have something like Hibernate <a href="http://docs.jboss.org/hibernate/stable/core/reference/en/html/mapping.html#mapping-declaration-property" target="_blank">property access config</a> that defines the strategy for accessing the property value but it still lacks the feature for associations.<strong></strong></p>
<h2>Testing</h2>
<p>With this approach I believe testing becomes more simple. I&#8217;ve created tests for the pure domain and just by including a different file I can test everything hooked up with infrastructure without rewriting the tests. To make things easier, I created two Rake tasks for testing: &#8216;rake test:domain&#8217; and &#8216;rake test:infrastructure&#8217;. I think they look a bit ugly at the moment but here we go:</p>
<pre style="color:#d1d1d1;background:#000000;font-size:12px;">namespace :<span style="color:#e66170;font-weight:bold;">test</span> <span style="color:#e66170;font-weight:bold;">do</span>
  task :enviroment_domain <span style="color:#e66170;font-weight:bold;">do</span> &#124;t&#124;
    ENV<span style="color:#d2cd86;">[</span><span style="color:#00c4c4;">'DDD_EXAMPLE_HELPER'</span><span style="color:#d2cd86;">]</span> <span style="color:#d2cd86;">=</span> Pathname<span style="color:#d2cd86;">(</span>__FILE__<span style="color:#d2cd86;">)</span><span style="color:#d2cd86;">.</span>dirname <span style="color:#d2cd86;">+</span> <span style="color:#00c4c4;">'tests'</span> <span style="color:#d2cd86;">+</span> <span style="color:#00c4c4;">'domain_helper'</span>
  <span style="color:#e66170;font-weight:bold;">end</span>

  task :enviroment_infrastructure <span style="color:#e66170;font-weight:bold;">do</span> &#124;t&#124;
    ENV<span style="color:#d2cd86;">[</span><span style="color:#00c4c4;">'DDD_EXAMPLE_HELPER'</span><span style="color:#d2cd86;">]</span> <span style="color:#d2cd86;">=</span> Pathname<span style="color:#d2cd86;">(</span>__FILE__<span style="color:#d2cd86;">)</span><span style="color:#d2cd86;">.</span>dirname <span style="color:#d2cd86;">+</span> <span style="color:#00c4c4;">'tests'</span> <span style="color:#d2cd86;">+</span> <span style="color:#00c4c4;">'infrastructure_helper'</span>
  <span style="color:#e66170;font-weight:bold;">end</span>

  Rake::TestTask<span style="color:#d2cd86;">.</span><span style="color:#e66170;font-weight:bold;">new</span><span style="color:#d2cd86;">(</span>:domain <span style="color:#d2cd86;">=</span>&#62; :enviroment_domain<span style="color:#d2cd86;">)</span> <span style="color:#e66170;font-weight:bold;">do</span> &#124;t&#124;
    t<span style="color:#d2cd86;">.</span>libs &#60;&#60; <span style="color:#00c4c4;">"tests"</span>
    t<span style="color:#d2cd86;">.</span>test_files <span style="color:#d2cd86;">=</span> FileList<span style="color:#d2cd86;">[</span><span style="color:#00c4c4;">"tests/domain/**/*_test.rb"</span><span style="color:#d2cd86;">]</span>
    t<span style="color:#d2cd86;">.</span>verbose <span style="color:#d2cd86;">=</span> <span style="color:#e66170;font-weight:bold;">true</span>
  <span style="color:#e66170;font-weight:bold;">end</span>

  Rake::TestTask<span style="color:#d2cd86;">.</span><span style="color:#e66170;font-weight:bold;">new</span><span style="color:#d2cd86;">(</span>:infrastructure <span style="color:#d2cd86;">=</span>&#62; :enviroment_infrastructure<span style="color:#d2cd86;">)</span> <span style="color:#e66170;font-weight:bold;">do</span> &#124;t&#124;
    t<span style="color:#d2cd86;">.</span>libs &#60;&#60; <span style="color:#00c4c4;">"tests"</span>
    t<span style="color:#d2cd86;">.</span>test_files <span style="color:#d2cd86;">=</span> FileList<span style="color:#d2cd86;">[</span><span style="color:#00c4c4;">"tests/domain/**/*_test.rb"</span><span style="color:#d2cd86;">]</span> <span style="color:#d2cd86;">+</span> FileList<span style="color:#d2cd86;">[</span><span style="color:#00c4c4;">"tests/infrastructure/**/*_test.rb"</span><span style="color:#d2cd86;">]</span>
    t<span style="color:#d2cd86;">.</span>verbose <span style="color:#d2cd86;">=</span> <span style="color:#e66170;font-weight:bold;">true</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
<span style="color:#e66170;font-weight:bold;">end</span></pre>
<h3>Test Case</h3>
<pre style="color:#d1d1d1;background:#000000;font-size:12px;"><span style="color:#e66170;font-weight:bold;">require</span> ENV<span style="color:#d2cd86;">[</span><span style="color:#00c4c4;">'DDD_EXAMPLE_HELPER'</span><span style="color:#d2cd86;">]</span>

<span style="color:#e66170;font-weight:bold;">class</span> CustomerRepositoryTest &#60; Test::Unit::TestCase
  <span style="color:#9999a9;"># ...</span>
  <span style="color:#e66170;font-weight:bold;">def</span> test_create
    customer <span style="color:#d2cd86;">=</span> Customer<span style="color:#d2cd86;">.</span><span style="color:#e66170;font-weight:bold;">new</span><span style="color:#d2cd86;">(</span><span style="color:#00c4c4;">'customer'</span>, <span style="color:#008c00;">1500</span><span style="color:#d2cd86;">)</span>
    CustomerRepository<span style="color:#d2cd86;">.</span>store<span style="color:#d2cd86;">(</span>customer<span style="color:#d2cd86;">)</span>
    assert_not_nil<span style="color:#d2cd86;">(</span>customer<span style="color:#d2cd86;">.</span>id<span style="color:#d2cd86;">)</span>
  <span style="color:#e66170;font-weight:bold;">end</span>
  <span style="color:#9999a9;"># ...</span>
<span style="color:#e66170;font-weight:bold;">end</span></pre>
<p>I believe this approach increases experimentation because we are free to work with our domain without worrying about persistence issues as if we were using Rails ActiveRecord. Rails AR need us to set up DB tables by running migrations in order to use the entities and have access to the properties.</p>
<h2>Project Structure</h2>
<p><img class="aligncenter size-full wp-image-108" title="structure" src="http://dddonruby.wordpress.com/files/2009/05/structure1.jpg" alt="structure" width="280" height="673" /></p>
<h2>Conclusion</h2>
<p>This whole thing might seem weird if you are used to Rails AR, but the fact that we have our domain totaly decoupled from infrastructure issues is important because as technology changes and shifts, and as our domain layer is burdened with complex computer science problems, things will most certainly change.  Keeping the <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">heart of the software</a> decoupled from tools allows those changes to be easier (XP ?).</p>
<p>That&#8217;s it! I&#8217;d like to thank <a href="http://blog.michaelbrennan.net/">Michael Brennan</a> and <a href="http://guilherme.pro/">Guilherme Chapiewski</a> for reviewing  and contributing with ideas for this post and <a href="http://www.linkedin.com/pub/sam-smoot/6/23b/881">Sam Smoot</a> for also reviewing and helping me out with Clipper.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Includes &amp; Eager Loading]]></title>
<link>http://bugsneedfix.wordpress.com/2009/06/08/includes-eager-loading/</link>
<pubDate>Sun, 07 Jun 2009 14:27:04 +0000</pubDate>
<dc:creator>Fadhli</dc:creator>
<guid>http://bugsneedfix.wordpress.com/2009/06/08/includes-eager-loading/</guid>
<description><![CDATA[I&#8217;m figuring out something in my rails app.  I&#8217;m figuring out which one&#8217;s the wors]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I&#8217;m figuring out something in my rails app.  I&#8217;m figuring out which one&#8217;s the worst:</p>
<p>Eager loading 100 rows of data you don&#8217;t actually need at the moment</p>
<p>or</p>
<p>10 queries giving 10 result set at once?</p>
<p>Here&#8217;s the code to explain it.</p>
<p><code><strong> </strong></code></p>
<pre class="brush: ruby;">

@event = Event.find(params[:event_id])

@event_attendees = @event.attendees.paginate(:page =&gt; params[:page], :per_page =&gt; 10)
</pre>
<p>In the view, for each attendees, it&#8217;s calling a purchase record. Since I&#8217;m using will_paginate and setting 10 records per page, for every 10 record of attendees, there&#8217;s 10 queries for a purchase record. Here&#8217;s the following SQL that will be generated:</p>
<pre class="brush: sql;">
SELECT * FROM `attendees` WHERE (`attendees`.event_id = 4)

SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = 1) LIMIT 1
SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = 2) LIMIT 1
SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = 3) LIMIT 1
SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = 4) LIMIT 1
SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = 5) LIMIT 1
SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = 6) LIMIT 1
SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = 7) LIMIT 1
SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> LIMIT 1
SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = 9) LIMIT 1
SELECT * FROM `purchases` WHERE (purchasable_type = 'Attendee' and purchasable_id = 10) LIMIT 1
</pre>
<p>Clearly you can that see the above code creates a n + 1 problem.</p>
<p>So I tried to modified it using eager loading like the following:</p>
<pre class="brush: ruby;">
@event_attendees = @event.attendees.paginate(:include =&gt; :purchase, :page =&gt; params[:page], :per_page =&gt; 10)
</pre>
<p>Here&#8217;s the following SQL query generated:</p>
<pre class="brush: sql;">
SELECT * FROM `attendees` WHERE (`attendees`.event_id = 4)
SELECT `purchases`.* FROM `purchases` WHERE (`purchases`.`purchasable_id` IN (1,2,3,4..100) and `purchases`.`purchasable_type` = 'Attendee')
 # query is shorten for brevity
</pre>
<p>You can see that it&#8217;s using 1 query that fetches 100 rows of data. At first I thought that it will limit the eager loading with my will_paginate per page settings. But clearly for every page that I&#8217;m viewing, it&#8217;s calling that query hence returning 100 rows of data for each page I&#8217;m viewing.</p>
<p>At the moment I&#8217;m using the query without eager loading. Simply because I&#8217;m concern the app is fetching 100 rows that I don&#8217;t need at once. I have no idea how to limit an eager loading association base on will _paginate per_page. Or probably I could eager load once and keep in cache. Or does rails does that automatically?</p>
<p>Will investigate though. Oh well, back to work!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[ Comparison &lt;=&gt; operator on string attributes of ActiveRecord objects]]></title>
<link>http://workbooks.wordpress.com/2009/06/05/comparison-operator-on-string-attributes-of-activerecord-objects/</link>
<pubDate>Fri, 05 Jun 2009 09:45:47 +0000</pubDate>
<dc:creator>Chris</dc:creator>
<guid>http://workbooks.wordpress.com/2009/06/05/comparison-operator-on-string-attributes-of-activerecord-objects/</guid>
<description><![CDATA[Here&#8217;s a little gotcha for you which caught me out by surprise, obvious when you think about i]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><br />
Here&#8217;s a little gotcha for you which caught me out by surprise, obvious when you think about it, but irritating if you miss it: the  ruby  String comparison operator does <strong>case-sensitive</strong> comparisons.</p>
<pre class="brush: ruby;">
# Good:
['C', 'b', 'A', 'D'].sort #=&#62; ['A', 'b', 'C', 'D']

# Bad (what &#60;=&#62; gives you out the box):
['C', 'b', 'A', 'D'].sort #=&#62; ['A', 'C', 'D', 'b']
</pre>
<p>For a nice efficient implementation of a AR model comparitor use the String#casecmp method for a <strong>case-insensitive</strong> comparison:</p>
<pre class="brush: ruby;">
class MyObject
  def &#60;=&#62;(other)
    self.my_attribute.casecmp(other.my_attribute)
  end
end
</pre>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Overriding fundamental ActiveRecord methods (like destroy) whilst preserving callbacks]]></title>
<link>http://workbooks.wordpress.com/2009/06/05/overriding-fundamental-activerecord-methods-like-destroy-whilst-preserving-callbacks/</link>
<pubDate>Fri, 05 Jun 2009 09:44:34 +0000</pubDate>
<dc:creator>Chris</dc:creator>
<guid>http://workbooks.wordpress.com/2009/06/05/overriding-fundamental-activerecord-methods-like-destroy-whilst-preserving-callbacks/</guid>
<description><![CDATA[OK, so you&#8217;ve decided that it&#8217;s a good idea for you to override one of the fundamental m]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><br />
OK, so you&#8217;ve decided that it&#8217;s a good idea for you to override one of the fundamental methods on one of your ActiveRecord models.  But in doing so, you have discovered that all of a sudden your callbacks have stopped working.</p>
<p>The reason for this is when your class is loaded, <a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html">ActiveRecord::Callbacks</a> have already hooked in the callback methods around the relevant methods using <a href="http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Module.html#M001188">alias_method_chain</a> meaning that the once named destroy method is now called destroy_without_callbacks.</p>
<p>So, to actually override the destroy method, use the following code:</p>
<pre class="brush: ruby;">
def destroy_without_callbacks
  unless new_record?
    # do your code here
  end
  freeze
end
</pre>
<p>Note that the implementations will differ for other methods e.g. create, so you should check the ActiveRecord base class to see what should be in there.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Rails &amp; named_scope]]></title>
<link>http://thailehuy.wordpress.com/2009/05/18/rails-named_scope/</link>
<pubDate>Mon, 18 May 2009 10:01:43 +0000</pubDate>
<dc:creator>thailehuy</dc:creator>
<guid>http://thailehuy.wordpress.com/2009/05/18/rails-named_scope/</guid>
<description><![CDATA[Source: http://mattpayne.ca/blog/post/named-scope Lately everyone has been going mad over a relative]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Source: <a href="http://mattpayne.ca/blog/post/named-scope" target="_blank">http://mattpayne.ca/blog/post/named-scope</a></p>
<div class="post_body">
<p>Lately everyone has been going mad over a relatively new addition to rails: <a title="named_scope" href="http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality" target="_blank">named_scope</a>. Up until now, I hadn&#8217;t had the chance to try it out. I always just assumed that it was more syntactic fluff that seems to accumulate. Wow, was I wrong! It&#8217;s an unbelievably cool and useful idea. Here&#8217;s a really simple example. Say I have 2 models: Country and Region. They are as you would expect. A Region belongs to a Country and a Country has many Regions, etc. I use them pretty much for dropdown lists and things like that. Here&#8217;s some code:</p>
<div class="dp-highlighter">
<ol class="dp-rb">
<li class="alt"><span><span class="keyword">class</span><span> Region &#60; ActiveRecord::Base </span></span></li>
<li><span> belongs_to <span class="symbol">:country</span><span> </span></span></li>
<li class="alt"><span><span class="keyword">end</span></span></li>
<li class="alt"><span><span class="keyword">class</span><span> Country &#60; ActiveRecord::Base </span></span></li>
<li><span> has_many <span class="symbol">:regions</span><span> </span></span></li>
<li class="alt"><span><span class="keyword">end</span><span> </span></span></li>
</ol>
</div>
<pre class="ruby" style="display:none;">class Region &#60; ActiveRecord::Base
  belongs_to :country
end

class Country &#60; ActiveRecord::Base
  has_many :regions
end</pre>
<p>Prior to named_scope, if you wanted to get all Regions in alphabetical order (as an example), you&#8217;d have to do something like:</p>
<div class="dp-highlighter">
<ol class="dp-rb">
<li class="alt"><span><span class="keyword">class</span><span> Region &#60; ActiveRecord::Base </span></span></li>
<li><span> <span class="comment">#other code</span><span> </span></span></li>
<li class="alt"><span> <span class="keyword">def</span><span> </span><span class="keyword">self</span><span>.ordered </span></span></li>
<li><span> find(<span class="symbol">:all</span><span>, </span><span class="symbol"> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder</span><span> =&#62; </span><span class="string">&#8220;name ASC&#8221;</span><span>) </span></span></li>
<li class="alt"><span> <span class="keyword">end</span><span> </span></span></li>
<li><span><span class="keyword">end</span><span> </span></span></li>
</ol>
</div>
<pre class="ruby" style="display:none;">class Region &#60; ActiveRecord::Base
  #other code
  def self.ordered
    find(:all, <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder =&#62; "name ASC")
  end
end</pre>
<p>Which was ok, but this is nicer:</p>
<div class="dp-highlighter">
<ol class="dp-rb">
<li class="alt"><span><span class="keyword">class</span><span> Region &#60; ActiveRecord::Base </span></span></li>
<li><span> named_scope <span class="symbol"> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rdered</span><span>, </span><span class="symbol"> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder</span><span> =&#62; </span><span class="string">&#8220;name ASC&#8221;</span><span> </span></span></li>
<li class="alt"><span> <span class="comment">#other code</span><span> </span></span></li>
<li><span><span class="keyword">end</span><span> </span></span></li>
</ol>
</div>
<pre class="ruby" style="display:none;">class Region &#60; ActiveRecord::Base
  named_scope <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rdered, <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder =&#62; "name ASC"
  #other code
end</pre>
<p>This creates a method on the Region class called ordered that can simply be called.</p>
<p>OK, so that&#8217;s cool and all, but really not that big a deal, right? Well, no &#8211; until you consider that you can chain calls to named_scope, thus adding more and more constraints. For example:</p>
<div class="dp-highlighter">
<ol class="dp-rb">
<li class="alt"><span><span class="keyword">class</span><span> Region &#60; ActiveRecord::Base </span></span></li>
<li><span> belongs_to <span class="symbol">:country</span><span> </span></span></li>
<li class="alt"><span> named_scope <span class="symbol"> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rdered</span><span>, </span><span class="symbol"> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder</span><span> =&#62; </span><span class="string">&#8220;name ASC&#8221;</span><span> </span></span></li>
<li><span> named_scope <span class="symbol">:by_country</span><span>, lambda { &#124;c&#124; { </span><span class="symbol">:conditions</span><span> =&#62; [</span><span class="string">"country_id = ?"</span><span>, c.id] } } </span></span></li>
<li class="alt"><span> named_scope <span class="symbol">:containing</span><span>, lambda { &#124;s&#124; { </span><span class="symbol">:conditions</span><span> =&#62; [</span><span class="string">"name like ?"</span><span>, </span><span class="string">"%#{s}%"</span><span>] } } </span></span></li>
<li><span><span class="keyword">end</span></span></li>
<li><span><span class="keyword">class</span><span> Runner </span></span></li>
<li class="alt"><span> c = Country.find_by_name(<span class="string">&#8220;Canada&#8221;</span><span>) </span></span></li>
<li><span> regions = Region.by_country(c).containing(<span class="string">&#8220;A&#8221;</span><span>).ordered </span></span></li>
<li class="alt"><span> puts <span class="string">&#8220;Provinces in Canada containing the letter A in ascending order: #{regions.inspect}&#8221;</span><span> </span></span></li>
<li><span><span class="keyword">end</span><span> </span></span></li>
</ol>
</div>
<pre class="ruby" style="display:none;">class Region &#60; ActiveRecord::Base
  belongs_to :country
  named_scope <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rdered, <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder =&#62; "name ASC"
  named_scope :by_country, lambda { &#124;c&#124; { :conditions =&#62; ["country_id = ?", c.id] } }
  named_scope :containing, lambda { &#124;s&#124; { :conditions =&#62; ["name like ?", "%#{s}%"] } }
end

class Runner
 c = Country.find_by_name("Canada")
 regions = Region.by_country(c).containing("A").ordered
 puts "Provinces in Canada containing the letter A in ascending order: #{regions.inspect}"
end</pre>
<p>This generates SQL that looks like this:</p>
<p>SELECT * FROM `regions` WHERE ((name like &#8216;%A%&#8217;) AND (country_id = 1)) ORDER BY name ASC</p>
<p>Another reason that I like name_scope is that because models such as these are frequently eused in dropdowns, etc, you can use named scope to return a very lightweight version of the class, while excluding attributes that are unnecessary for a simple dropdown. For example:</p>
<div class="dp-highlighter">
<ol class="dp-rb">
<li class="alt"><span><span class="keyword">class</span><span> Region &#60; ActiveRecord::Base </span></span></li>
<li><span> belongs_to <span class="symbol">:country</span><span> </span></span></li>
<li class="alt"><span> named_scope <span class="symbol"> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rdered</span><span>, </span><span class="symbol"> <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder</span><span> =&#62; </span><span class="string">&#8220;name ASC&#8221;</span><span> </span></span></li>
<li><span> named_scope <span class="symbol">:by_country</span><span>, lambda { &#124;c&#124; { </span><span class="symbol">:conditions</span><span> =&#62; [</span><span class="string">"country_id = ?"</span><span>, c.id] } } </span></span></li>
<li class="alt"><span> named_scope <span class="symbol">:containing</span><span>, lambda { &#124;s&#124; { </span><span class="symbol">:conditions</span><span> =&#62; [</span><span class="string">"name like ?"</span><span>, </span><span class="string">"%#{s}%"</span><span>] } } </span></span></li>
<li><span> named_scope <span class="symbol">:simple</span><span>, </span><span class="symbol">:select</span><span> =&#62; </span><span class="string">&#8220;id, name&#8221;</span><span> </span></span></li>
<li class="alt"><span><span class="keyword">end</span><span> </span></span></li>
</ol>
</div>
<pre class="ruby" style="display:none;">class Region &#60; ActiveRecord::Base
  belongs_to :country
  named_scope <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rdered, <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> rder =&#62; "name ASC"
  named_scope :by_country, lambda { &#124;c&#124; { :conditions =&#62; ["country_id = ?", c.id] } }
  named_scope :containing, lambda { &#124;s&#124; { :conditions =&#62; ["name like ?", "%#{s}%"] } }
  named_scope :simple, :select =&#62; "id, name"
end</pre>
<p>This allows me to only bring back the attributes that I need. And again, it could be chained with other named scopes</p>
<p>I think that this is a very powerful concept that allows developers to write more DRY and readable code.</p></div>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Some topics I'm willing to discuss]]></title>
<link>http://dddonruby.wordpress.com/2009/05/14/some-topics-im-willing-to-discuss/</link>
<pubDate>Thu, 14 May 2009 06:11:35 +0000</pubDate>
<dc:creator>Fábio Rehm</dc:creator>
<guid>http://dddonruby.wordpress.com/2009/05/14/some-topics-im-willing-to-discuss/</guid>
<description><![CDATA[Before getting down to business, I want to present the topics I&#8217;m willing to go through here: ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Before getting down to business, I want to present the topics I&#8217;m willing to go through here:</p>
<ol>
<li><strong>Finding a nice way to decouple our domain from infrastructure</strong> &#8211; The discussion will be about forgetting Rails ActiveRecord in order to achieve persistence ignorance.</li>
<li><strong>Porting DDDSample to Ruby and Rails &#8211; </strong>I haven&#8217;t seen any movement towards that yet so we could get some people together and make this happen.</li>
<li><strong>Finding a way to make usage of a Domain Specific Language in DDDSample</strong>.</li>
</ol>
<p>And that&#8217;s it! I still need to learn a bit more on the last topic but I hope that when we get to it I&#8217;m already confortable with its concepts and ideas.</p>
<h3>Coming up</h3>
<ul>
<li>A comparisson between a common &#8220;C# / Java + (N)Hibernate&#8221; implementation of some  <a href="http://domaindrivendesign.org/node/121" target="_blank">Model Driven Design</a> <a href="http://dddsample.sourceforge.net/patterns-reference.html" target="_blank">building blocks</a> used in DDD and my one.</li>
</ul>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Motivation]]></title>
<link>http://dddonruby.wordpress.com/2009/05/12/motivation/</link>
<pubDate>Tue, 12 May 2009 06:32:23 +0000</pubDate>
<dc:creator>Fábio Rehm</dc:creator>
<guid>http://dddonruby.wordpress.com/2009/05/12/motivation/</guid>
<description><![CDATA[I started to think about the relation of DDD and Ruby /Rails when I was thinking about the subject o]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I started to think about the relation of DDD and Ruby /Rails when I was thinking about the subject of my final paper for university. First I wanted to write about DDD only, it is subject that doesn&#8217;t seem to have much attention among the people that I know. But after reading an Eric Evans (author of <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215" target="_blank">the blue book</a>) <a href="http://www.infoq.com/articles/eric-evans-ddd-matters-today" target="_blank">interview</a> for <a href="http://www.infoq.com/minibooks/domain-driven-design-quickly" target="_blank">InfoQ &#8211; Domain-Driven Design Quickly</a> book, I realized that DDD + Ruby + Rails was something that I should give a try. For the same reasons I agree with him in the way that Ruby can be a nice platform for doing DDD:</p>
<blockquote><p><span style="text-decoration:underline;"><strong>InfoQ</strong></span>:<strong> </strong>Technology platforms (Java, .NET, Ruby, others) are continually evolving. How does Domain Driven Design fit in?</p>
<p><span style="text-decoration:underline;"><strong>EVANS</strong></span>: [...] DDD is not specific to a technology platform, but some platforms give more expressive ways of creating business logic, and some platforms have less distracting clutter.<br />
[...]  Then you have the new-comers like Ruby. <strong>Ruby has a very expressive syntax, and at this basic level it should be a very good language for DDD (although I haven&#8217;t heard of much actual use of it in those sorts of applications yet)</strong>. Rails has generated a lot of excitement because it finally seems to make creation of Web UIs as easy as UIs were back in the early 1990s, before the Web. Right now, this capability has mostly been applied to building some of the vast number of Web applications which don&#8217;t have much domain richness behind them, since even these have been painfully difficult in the past. <strong>But my hope is that, as the UI implementation part of the problem is reduced, that people will see this as an opportunity to focus more of their attention on the domain. If Ruby usage ever starts going in that direction, I think it could provide an excellent platform for DDD. (A few infrastructure pieces would probably have to be filled in.)</strong><br />
More out on the cutting-edge are the efforts in the area of domain-specific languages (<strong>DSLs</strong>), which I have long believed could be the next big step for DDD. To date, we still don&#8217;t have a tool that really gives us what we need. But people are experimenting more than ever in this area, and that makes me hopeful.<br />
Right now, as far as I can tell, most people attempting to apply DDD are working in Java or .Net, with a few in Smalltalk. So it is the positive trend in the Java world that is having the immediate effect.</p></blockquote>
<p>So&#8230; The book dates from Dec 08, 2006. Has anyone seen a movement toward this direction? I googled about it and I didn&#8217;t find anyone talking about a succesful experimentation with the two of them (I&#8217;ll add more to that in a minute). Maybe I&#8217;m using the wrong keywords or maybe there&#8217;s really nothing about. The fact is that there are lots and lots of references and examples of how it works in the context of .NET and Java (and I think some in PHP) but I couldn&#8217;t find anything related to Ruby (and Rails).</p>
<p>All that made me come up with the subject for my final paper which will probably be called &#8220;Applying Domain-Driven Design with Ruby and Rails&#8221; and this blog came as a support for my thoughts.</p>
<h2>What (maybe) stop us from doing &#8220;DDD on Ruby / Rails&#8221;?</h2>
<p>After some research I&#8217;ve organized a few links about the discussion:</p>
<ul>
<li><a href="http://tech.groups.yahoo.com/group/domaindrivendesign/message/12726" target="_blank">Discussion on Yahoo Groups</a></li>
<li><a href="http://www.blog.dannynet.net/archives/70" target="_blank">Domain-driven Ruby on Rails??</a></li>
<li><a href="http://andymaleh.blogspot.com/2007/10/domain-driven-or-database-driven.html" target="_blank">Domain-Driven or Database-Driven?</a></li>
<li><a href="http://mortslikeus.blogspot.com/2009/01/active-record-and-ddd.html">Active Record and DDD</a></li>
</ul>
<p>They maybe sum up the reasons that people might think we are not able to create an DDD-ish application in Ruby / Rails.</p>
<p style="padding-left:30px;"><span style="text-decoration:underline;"><strong> </strong></span></p>
<p>Most of the arguments that I found are that Rails was created for data-centric applications that involves only <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete" target="_blank">CRUD</a>. If that is true, it ends up beeing one of the <a href="http://devlicio.us/blogs/casey/archive/2009/02/18/ddd-what-kind-of-applications-is-it-suited-to.aspx" target="_blank">95% of the applications</a> that won&#8217;t benefit from applying DDD. The other main argument probably is that in Rails the <a href="http://en.wikipedia.org/wiki/Domain_model" target="_blank">domain model</a> <a href="http://domaindrivendesign.org/node/109" target="_blank">entities</a> are implemented using <a href="http://martinfowler.com/eaaCatalog/activeRecord.html" target="_blank">Active Record pattern</a> and that might &#8220;break&#8221; DDD since it <a href="http://mortslikeus.blogspot.com/2009/01/active-record-and-ddd.html" target="_blank">violates</a> the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank">Single Responsibility Principle</a> (and maybe <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" target="_blank">Liskov substition principle</a> as discussed <a href="http://tech.groups.yahoo.com/group/domaindrivendesign/message/12726" target="_blank">here</a>) and we are bound to the underlaying persistence (which can be  <a href="http://tech.groups.yahoo.com/group/domaindrivendesign/message/3755" target="_blank">considered as a distraction</a>).</p>
<p>But&#8230; It is a fact that Rails is a highly productive framework. So, what if we could bring the two worlds together? Instead of not fighting our framework, what if we were able to &#8220;quickly&#8221; build more complex applications with the combination DDD + Ruby + Rails? It will probably be not so easy but I&#8217;m willing to give it a try.</p>
<p>I&#8217;ve done some experimentation in that way and I will be posting about it on the next days so that we can discuss it. For now, I can say that I believe that I found a good way to decouple our domain from infrastructure. I&#8217;ve managed to model my domain objects as POROs (plain old ruby objects) taking advantage of Ruby&#8217;s <a href="http://www.ruby-lang.org/en/documentation/quickstart/3/" target="_blank">open classes</a> and <a href="http://garbageburrito.com/blog/entry/237/ruby-mixins-the-magic-behind-plugins" target="_blank">modules mixins</a>.</p>
<p>My plan is to make an attempt to rewrite the <a href="http://dddsample.sourceforge.net/" target="_blank">DDDSample application</a> writen in Java (I&#8217;ll just have to check if someone has a problem with that)</p>
<h2>Got something to add? Please leave a comment!</h2>
<p>Maybe you think I&#8217;m crazy to start this discussion or maybe you are pretty sure the we can&#8217;t put DDD and Ruby / Rails together, but feel free to drop by and express your opinion. The main purpose of this blog is to concentrate discussion about the topics.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Double Shot #447]]></title>
<link>http://afreshcup.com/2009/05/07/double-shot-447/</link>
<pubDate>Thu, 07 May 2009 10:23:12 +0000</pubDate>
<dc:creator>Mike Gunderloy</dc:creator>
<guid>http://afreshcup.com/2009/05/07/double-shot-447/</guid>
<description><![CDATA[Today needs to be about writing code. Record Filter &#8211; A pure-ruby DSL to replace SQL in Active]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Today needs to be about writing code.</p>
</ul>
<li><strong><a href="http://aub.github.com/record_filter/">Record Filter</a></strong> &#8211; A pure-ruby DSL to replace SQL in ActiveRecord. Personally, I&#8217;d be happy with more SQL, but to each their own.</li>
<li><strong><a href="http://www.ultrasaurus.com/sarahblog/2009/05/on-apis-more-craft-less-magic/">on APIs: more craft, less magic</a></strong> &#8211; &#8220;Rails seems to assume that you want to expose your database object model transparently through your API.  In my experience, this is rarely what you want to do. In fact, it is a crazy way to live.&#8221;</li>
<li><strong><a href="http://www.bryanthompson.tv/posts/show/5264646c-6708-40ea-ae0e-5c813d0054f8">A git-style wiki system</a></strong> &#8211; Bryan Thompson ponders a way to help Rails newbies with common questions.</li>
</ul>
</div>]]></content:encoded>
</item>

</channel>
</rss>
