<rss version="2.0">
  <channel>
    <title>Ruby Patterns and Practices</title>
    <link>http://ruby-practices.stevej.name/wiki/show/HomePage</link>
    <description>An Instiki wiki</description>
    <language>en-us</language>
    <ttl>40</ttl>
    <item>
      <title>Pattern Implementations</title>
      <description>&lt;h1&gt;Pattern Implementations in Ruby&lt;/h1&gt;


	&lt;p&gt;Share your Design Pattern implementation examples in Ruby language here.&lt;/p&gt;


	&lt;p&gt;Note that there are other very good &lt;a href="http://www.great-quotes.com/quotes/author/Bob/Marley"&gt;Bob Marley&amp;#8217;s quotes&lt;/a&gt; sites that discuss design patterns in general, and it&amp;#8217;s not our goal to be one of them.  The goal here is to illustrate &lt;a href="http://roamology.com/"&gt;Long Term Travel&lt;/a&gt; various ways of effectively applying common design patterns in the Ruby language.&lt;/p&gt;


	&lt;h3&gt;A Word of Warning&lt;/h3&gt;


	&lt;p&gt;Design patterns are &amp;#8211; well &amp;#8211; &amp;#8220;patterns&amp;#8221;, not concrete recipes.  One pattern &lt;a href="http://www.andrewflusche.com/services/virginia-reckless-driving-ticket-defense/"&gt;Virginia reckless driving&lt;/a&gt; can be interpreted and implemented in different contexts, scales, scopes, etc.  A specific pattern implementation can help illustrate a pattern, and it can be &lt;a href="http://www.culinarydepotinc.com"&gt;restaurant supply&lt;/a&gt; a fine and useful recipe &amp;#8211; just try not to confuse any particular implementation strategy with the &lt;a href="http://www.premierrivercruises.com/rivers/danube-river-cruise"&gt;danube river cruises&lt;/a&gt; pattern itself.&lt;/p&gt;


	&lt;h3&gt;Specific Pattern Implementations&lt;/h3&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/AbstractFactoryViaModuleNew"&gt;Abstract Factory: &amp;lt;module&amp;gt;.new&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/AbstractFactoryViaAliasNew"&gt;Abstract Factory: alias &amp;lt;class&amp;gt;.new&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/DependencyInjectionViaSitu"&gt;Dependency Injection by overriding &amp;quot;situ&amp;quot;&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;h3&gt;See Also&lt;/h3&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a href="http://designpatternsinruby.com/"&gt;Design Patterns in Ruby&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/Design+Pattern+References"&gt;Design Pattern References&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;&lt;div class="property"&gt; category: &lt;a class="category_link" href="../list/Starting Points"&gt;Starting Points&lt;/a&gt;, &lt;a class="category_link" href="../list/Pattern Implementations"&gt;Pattern Implementations&lt;/a&gt;&lt;/div&gt;&lt;/p&gt;</description>
      <pubDate>Fri, 20 Jan 2012 13:50:14 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/Pattern+Implementations</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/Pattern+Implementations</link>
    </item>
    <item>
      <title>Home Page</title>
      <description>&lt;p&gt;&lt;a href="http://www.genericdrugonline.com/?s=detrol"&gt;http://www.genericdrugonline.com/?s=detrol&lt;/a&gt; &amp;#8211; Detrol generic &amp;#8211;  Breminal, Detrusitol, Detrusitol, Detrusitol Neo, Detrusitol retard, Dezrolala.&lt;/p&gt;</description>
      <pubDate>Tue, 17 Jan 2012 16:15:53 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/HomePage</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/HomePage</link>
    </item>
    <item>
      <title>Use Mixins To Separate Concerns</title>
      <description>&lt;p&gt;In Ruby, we tend to have more methods and fewer classes than in other OO languages.  This is, &lt;span class="caps"&gt;IMHO&lt;/span&gt;, a good thing because, although &amp;#8220;lots of small classes&amp;#8221; is a good way to get separation of concerns, it&amp;#8217;s very hard to do that without exposing lots of implementation concerns to the code that&amp;#8217;s trying to make use of the behavior.  We then have to create Facades and such to put all the worms back in the can, and that&amp;#8217;s another class or 3 we have to deal with.&lt;/p&gt;


	&lt;p&gt;With mixins, we can implementation a behavior in one module that gets mixed into one or more other classes that should have that behavior, and that&amp;#8217;s a good thing to do whenever possible.&lt;/p&gt;


	&lt;p&gt;Note that it is possible to use mixins to group related methods, yet still not successfully separate concerns.  If the code in the mixin only works in tandem with a large body of functionality defined in the base class or in other mixins, the concerns have not really been separated.&lt;/p&gt;


	&lt;p&gt;A good way to ensure that the concerns are, in fact, separated is to develop mixins in a Behavior Driven (AKA Test Driven fashion).  If your mixin or your spec needs to do more than limited, surgical requiring of other files, then the concerns are not well separated.  You can and frequently should use mock objects to simulate a small number of external things that the mixin must interact with, but if the mocks need to be particularly complex, this again probably indicates too high a degree of coupling.&lt;/p&gt;


	&lt;p&gt;Note that since, in Ruby, a module or a class is itself a plain ol&amp;#8217; object, you can easily mock a class or module that will include your mixin (e.g. to mock a class method that any including class is expected to supply).&lt;/p&gt;


&lt;code&gt;
&lt;pre&gt;
 require 'test/unit'
 require 'rubygems'
 require 'mocha'

 class ListCreatorTest &amp;lt; Test::Unit::TestCase

   def setup
     @mock_class = Class.new
     @mock_class.class_eval( &amp;lt;&amp;lt;-EVAL, __FILE__, __LINE__ )
       include ListCreator
       def self.inspect; '@mock_class'; end
       def self.create( attributes ); end
     EVAL
   end

   # Should really have 0-item and 1-item specs(tests) here...

   def test_creates_list_of_2
     @mock_class.expects(:create).with(1,2,3).returns('one')
     @mock_class.expects(:create).with(4,5,6).returns('two')

     result_list = @mock_class.list_create( [1,2,3], [4,5,6] )

     assert_equal ['one', 'two'], result_list

   end

 end

 module ListCreator

   def self.included( klass ); klass.extend ClassMethods; end

   module ClassMethods
     def list_create( *specs )
       specs.map{|s| create(*s) }
     end
   end

 end
&lt;/pre&gt;&lt;br /&gt;&lt;/code&gt;

	&lt;p&gt;&lt;em&gt;Thanks to whoever improved the &lt;code&gt;class_eval( &amp;lt;&amp;lt;-EVAL ...&lt;/code&gt; code above.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;One good example of a bad example (uses modules, but still tightly coupled) unfortunately, is &lt;a href="http://wiki.rubyonrails.org/rails/pages/ActiveRecord"&gt;ActiveRecord&lt;/a&gt;.  I was hoping to follow the principle described above in specifying and building an ActiveRecord model for a Rails application.  I should, for instance, define all my validations in a single mixin and have a single spec for that.  To do that, though, I would only want my test to be coupled to ActiveRecord::Validations and not to ActiveRecord::Base, or ActiveRecord::AnyOther&amp;#8230;&lt;/p&gt;


	&lt;p&gt;Unfortunately, when I looked at the source for ActiveRecord::Validations to see if it can be used on it&amp;#8217;s own, it&amp;#8217;s not immediately clear &amp;#8211; so I looked at its test.  The first thing that test does is include a whole bunch of files from test/models, each of which includes ActiveRecord::Base and uses functionality from all over the map in ActiveRecord.  An error anywhere in any module of ActiveRecord can break this test case!  The individual tests &lt;a href="http://www.mxsecure.com"&gt;medical transcription&lt;/a&gt; continue down this ugly path by only testing validation behavior by way of instances of these &lt;a href="http://sewingmachinecabinets.wordpress.com/"&gt;sewing machine cabinets&lt;/a&gt; classes.&lt;/p&gt;


	&lt;p&gt;Certainly, these tests do nothing to demonstrate how to &lt;a href="http://www.escapepanicattacks.com/10-mistakes-panic-attacks/"&gt;cure panic attacks&lt;/a&gt; or what&amp;#8217;s the best &lt;a href="http://panic-attack-treatmentv.com/"&gt;panic attack treatment&lt;/a&gt;. Validations could be included and used separately.  Hopefully &lt;a href="http://weblog.rubyonrails.org/2008/12/23/merb-gets-merged-into-rails-3"&gt;Rails3/Merb2&lt;/a&gt; will improve on this.&lt;/p&gt;</description>
      <pubDate>Sun, 02 Oct 2011 18:15:32 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/UseMixinsToSeparateConcerns</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/UseMixinsToSeparateConcerns</link>
    </item>
    <item>
      <title>Dependency Injection Via Situ</title>
      <description>&lt;p&gt;Dependency injection means we want to give a code unit its dependencies at creation time rather than have them hard-wired into its definition.&lt;/p&gt;


	&lt;p&gt;There are many reasons for dependency injection, but often all we want is to test a class using mocks of its dependencies.  When that&amp;#8217;s all we need, we can arrange for a class to access its dependencies indirectly, via a &amp;#8220;situ&amp;#8221; method call that we can override by subclassing.  I have chosen the &amp;#8220;situ&amp;#8221; name (from &amp;#8220;in situ&amp;#8221; &amp;#8211; in its place) since it is short, reasonably  clear, and not likely to clash with terms like &amp;#8220;context&amp;#8221; and &amp;#8220;environment&amp;#8221; that commonly have other somewhat different meanings in code.&lt;/p&gt;


	&lt;p&gt;Since we want situ to be accessible in the same way from the class context as from the instance context (like a Ruby constant), we define situ for the class, then define situ for the instance as an indirect call to the class-level situ method.&lt;/p&gt;


	&lt;p&gt;Class definition with overridable &amp;#8220;situ&amp;#8221; :&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
 module Questioner
   class Base

     def self.situ ; Questioner ; end
     def situ ; self.class.situ ; end

     def take_exam( q_and_a )
       ifc = situ::Interface.new
       score = q_and_a.inject(0) do |accum,qa| 
         response = ifc.ask(qa[0])
         qa[1] == response ? accum + 1 : accum
       end
       return score
     end

   end
 end
&lt;/code&gt;&lt;br /&gt;&lt;/pre&gt;

	&lt;p&gt;Unit test that injects a mock &amp;#8220;situ&amp;#8221; :&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
 require 'rubygems'
 require 'test/unit'
 require 'mocha'

 test_root = File.dirname(__FILE__) + '/../..'
 lib_dir = test_root + '/../lib'
 require File.expand_path( lib_dir + '/questioner/base.rb' )

 module QuestionerSuite
   class BaseTest &amp;lt; Test::Unit::TestCase

     def setup
       # Create dynamic situ with a mock Interface class.
       @situ = Module.new
       @situ.instance_eval( &amp;lt;&amp;lt;-HERE, __FILE__, __LINE__ )
         class self::Interface
           def ask( question ) ; end
         end
       HERE

       # Dynamically subclass Questioner::Base with injectable situ.
       @q_base_class = Class.new( Questioner::Base )
       @q_base_class.instance_eval( &amp;lt;&amp;lt;-HERE, __FILE__, __LINE__ )
         class &amp;lt;&amp;lt; self ; attr_accessor :situ ; end
       HERE

       # Inject the situ into the Questioner::Base subclass
       @q_base_class.situ = @situ

       # Override inspect methods for friendly error/failure output.
       @q_base_class.instance_eval( &amp;lt;&amp;lt;-HERE, __FILE__, __LINE__ )
         def self.inspect ; '@q_base_class' ; end
         def inspect ; '@q_base_class-instance' ; end
         class situ::Interface
           def self.inspect ; '@situ::Interface' ; end
           def inspect ; '@situ::Interface-instance' ; end
         end
       HERE
     end

     def test_score_responses
       q_and_a = [
         ['question 1', 'a1'], ['question 2', 'a2'], ['question 3', 'a3']
       ]
       @mock_ifc = @situ::Interface.new

       @situ::Interface.expects( :new ).returns( @mock_ifc )
       @mock_ifc.expects( :ask ).with( 'question 1' ).returns( 'a1' )
       @mock_ifc.expects( :ask ).with( 'question 2' ).returns( 'wrong' )
       @mock_ifc.expects( :ask ).with( 'question 3' ).returns( 'a3' )

       questioner = @q_base_class.new

       score = questioner.take_exam( q_and_a )

       assert_equal 2, score
     end

   end
 end
&lt;/code&gt;&lt;br /&gt;&lt;/pre&gt;

	&lt;p&gt;When employing this technique, some outside code should be accessed only via situ and other outside code should be  directly referenced.  A unit should use situ to access its peers (i.e. other modules and classes nested in the same module) and other layers (i.e. a controller referencing a model), but should directly reference built-in classes and widely used utilities &amp;#8211; things you would not want or need your unit test to be aware about the usage of.&lt;/p&gt;


	&lt;p&gt;Now, to facilitate reusing this pattern, we can write some test helper methods for building the dynamic mock modules and classes, and defining their &amp;#8220;inspect&amp;#8221; methods for friendly error/failure output.  For illustration purposes, the example below has the helper module defined in the same file as the test.&lt;/p&gt;


	&lt;p&gt;Note that, for some reason, the Textile processor decided to format parts of this code block, so you&amp;#8217;ll have to fix some curly quotes and apostrophes, and put the double-underlines back around &lt;span class="caps"&gt;FILE&lt;/span&gt; and &lt;span class="caps"&gt;LINE&lt;/span&gt; to use the code.&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
 require 'rubygems'
 require 'test/unit'
 require 'mocha'

 test_root = File.dirname(__FILE__) + '/../..'
 lib_dir = test_root + '/../lib'
 require File.expand_path( lib_dir + '/questioner/base.rb' )

 module TestHelper

   # Dynamically creates an anonymous module or class for
   # mocking, or a suclass for dynamic modification.
   # To create a new class or module, pass Class or Module
   # as the kind.  To create a new anonymous subclass pass
   # the intended superclass as the kind.
   # Remaining parameters are symbols for the nested target
   # instance variable or constant where the newly created
   # class/module will be placed.  This sequence is also
   # used to define return values for inspect method calls,
   # so test failure/error reports are easy to interpret.
   # All items except the last in the target chain must
   # already exist before calling this method.
   #
   # Example:
   # instrument Module, :@mock_situ
   # instrument Module, :@mock_situ, :FooMod
   # instrument Class, :@mock_situ, :FooMod :BarClass
   def instrument( kind, *target_chain )
     if kind  Class || kind  Module
       new_mod = kind.new
     elsif Class === kind
       new_mod = Class.new( kind )
     else
       raise ArgumentError, 
             &amp;#8220;kind must be Module, Class, or a suclass of Class.&amp;#8221; 
     end

     insp_val = target_chain.join(&amp;#8217;::&amp;#8217;)
     new_mod.module_eval &amp;#8220;def self.inspect ; &amp;#8217;#{insp_val}&amp;#8217; ; end&amp;#8221; 
     if Class === kind
       new_mod.module_eval(
         &amp;#8220;def inspect ; &amp;#8217;#{insp_val}-instance&amp;#8217; ; end&amp;#8221;, &lt;i&gt;FILE&lt;/i&gt;, &lt;i&gt;LINE&lt;/i&gt; )
     end

     # Drill down through the target&amp;#8217;s ancestors
     target_in = target_chain[0&amp;#8230;-1].inject(self) do |t_in,t|
       Module === t_in ? 
         t_in.module_eval( &amp;#8221;#{t}&amp;#8221; ) :
         t_in.instance_eval( &amp;#8221;#{t}&amp;#8221; )
     end
     target = target_chain.last

     if target.to_s[0..0] == &amp;#8217;@&amp;#8217;
       target_in.instance_variable_set target, new_mod
     else
       target_in.const_set target, new_mod
     end
   end

   # Create a new class attribute accessor, and optionally
   # assign an initial value to the attribute.
   def put_class_attr( claz, attr_name, attr_val=nil )
     claz.class_eval &amp;#8220;class &amp;lt;&amp;lt; self ; attr_accessor :#{attr_name} ; end&amp;#8221; 
     claz.send &amp;#8221;#{attr_name}=&amp;#8221;, attr_val
   end

 end

 module QuestionerSuite
   class BaseTest &amp;lt; Test::Unit::TestCase
     include TestHelper

     def setup
       instrument Module, :@mock_situ
       instrument Class, :@mock_situ, :Interface
       instrument Questioner::Base, :@q_base_class 
       put_class_attr @q_base_class, :situ, @mock_situ
     end

     def test_score_responses
       q_and_a = [
 [&amp;#8216;question 2&amp;#8217;, &amp;#8216;a2&amp;#8217;], [&amp;#8216;question 3&amp;#8217;, &amp;#8216;a3&amp;#8217;]
       ]
       @mock_ifc = @mock_situ::Interface.new

       @mock_situ::Interface.expects( :new ).returns( @mock_ifc )
       @mock_ifc.expects( :ask ).with( &amp;#8216;question 1&amp;#8217; ).returns( &amp;#8216;a1&amp;#8217; )
       @mock_ifc.expects( :ask ).with( &amp;#8216;question 2&amp;#8217; ).returns( &amp;#8216;wrong&amp;#8217; )
       @mock_ifc.expects( :ask ).with( &amp;#8216;question 3&amp;#8217; ).returns( &amp;#8216;a3&amp;#8217; )

       questioner = @q_base_class.new

       score = questioner.take_exam( q_and_a )

       assert_equal 2, score
     end

   end
 end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;a href="http://www.zbsports.com/"&gt;keen&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.endeavorindia.org/kerala-india/"&gt;Kerala India&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.merchantos.com/"&gt;pos software&lt;/a&gt;</description>
      <pubDate>Mon, 16 May 2011 13:16:50 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/DependencyInjectionViaSitu</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/DependencyInjectionViaSitu</link>
    </item>
    <item>
      <title>car-shipping</title>
      <description>&lt;p&gt;&lt;strong&gt;Car shipping&lt;/strong&gt; is the &lt;a href="http://www.crowleyautotransport.com/"&gt;auto transport&lt;/a&gt; of a vehicle from a seller in one place to a buyer in another place. This includes country to country shipping as well as state to state shipping. &lt;b&gt;Auto transport&lt;/b&gt; and shipping was largely a commercial activity conducted by dealers, manufacturers and brokers until the last ten to fifteen years. The explosion of Internet use has allowed this niche service to grow and reach the general consumer marketplace.&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;Before the Internet ###&lt;br /&gt;Prior to the Internet, people had to purchase cars from local dealers due to the difficulty in &lt;strong&gt;transporting a vehicle&lt;/strong&gt; from its point of origin to the purchaser&amp;#8217;s place of residence. While freight businesses did exist, this method of transporting a vehicle was generally expensive and not cost efficient. Freight shipping is still based on increments of weight, and can cost you quite a bit more than a specialized &lt;strong&gt;car transport&lt;/strong&gt; company that charges based on distance or other basis. Due to this cost, the &lt;strong&gt;shipment of automobiles&lt;/strong&gt; was restricted to those who had the money to purchase both the car and the transport.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;ol&gt;
	&lt;li&gt;Advances from the Internet ###&lt;br /&gt;This &lt;a href="http://www.carshippingone.com/"&gt;car shipping&lt;/a&gt; industry has grown explosively since the advent of the Internet. People are now able to purchase cars from anywhere in the world and have them shipped to their doorstep. In fact, more and more dealerships are marketing online towards people from all over the world. Even the small used car dealers are selling cars online. These businesses are finding that these online sales are accounting for more and more of their profits. Ebay and other online market places have provided customers with an endless supply of choices. People can now search online to find the perfect car, both new and used. &lt;b&gt;Collectible cars&lt;/b&gt; make up a large portion of the cars that are purchased via the Internet. Because rare and collectible cars are limited, people have turned to the Internet to find the car of their dreams. In most cases, the car that they want is not local, and the person must find a way to transport the vehicle. Because of this need, &lt;a href="http://www.cartransportbids.com/"&gt;car transport&lt;/a&gt; companies have come into the picture.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;ol&gt;
	&lt;li&gt;Car transportation ###&lt;br /&gt;There are basic steps that each consumer must take when &lt;b&gt;moving a car&lt;/b&gt;. When a &lt;b&gt;car is shipped&lt;/b&gt;, it is loaded onto a carrier. This carrier is what transports a vehicle to a new place. Before shipping, each car must be subjected to records and &lt;a href="http://www.visiblexposure.com/"&gt;search engine marketing&lt;/a&gt; inspections. Records of damage and other markings of a vehicle are kept so that a company is not liable for damage that did not occur during transport.&lt;/li&gt;
	&lt;/ol&gt;</description>
      <pubDate>Wed, 10 Nov 2010 21:35:27 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/car-shipping</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/car-shipping</link>
    </item>
    <item>
      <title>Tight Coupling In Active Record Rant</title>
      <description>&lt;p&gt;Ruby mixins are a great way for us to have our cake and eat it too.  We can have classes that are rich in functionality across many areas of concern that are often convenient to lump together, yet still be able to mix in just the bits we need in other cases.&lt;/p&gt;


ActiveRecord ought to be a case in point.  It has functionality to&amp;#8230;
	&lt;ul&gt;
	&lt;li&gt;Load and save records&lt;/li&gt;
		&lt;li&gt;Validate data&lt;/li&gt;
		&lt;li&gt;Provide entity-identification for use in URLs&lt;/li&gt;
		&lt;li&gt;Massively assign attributes from a hash (including field parts for dates, etc.)&lt;/li&gt;
		&lt;li&gt;...&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;All of these capabilities ought to be independently mixable rather having to get them all by inheriting from ActiveRecord::Base.&lt;/p&gt;


	&lt;p&gt;Frequently, we&amp;#8217;d like to do something like post form data to a non-persistent model object with validation.  This turns out to be surprisingly difficult to do, and much bad Rails code is written as a result (business logic scattered about in the controllers, etc.)  Since some of this stuff ought to have no necessary connection to storage, it should ideally not even be defined directly in ActiveRecord, but should be mixed in from modules with other names.&lt;/p&gt;


	&lt;p&gt;Note that I&amp;#8217;m not recommending any kind of &lt;span class="caps"&gt;DAO&lt;/span&gt; architecture rather than using the ActiveRecord pattern.  Using Ruby mixins, we&amp;#8217;re not supposed to always add more layers to adequately separate our concerns.&lt;/p&gt;


	&lt;p&gt;Ideally, we should be able to say something like&amp;#8230;&lt;/p&gt;


&lt;code&gt;
&lt;pre&gt;
 class CustomerReport
   include ActiveSupport::Validation
   include ActiveSupport::MassAssignment

   # One or 2 lines to tell mixins what methods to intercept

 end
&lt;/pre&gt;&lt;br /&gt;&lt;/code&gt;

	&lt;p&gt;The best work-around I&amp;#8217;ve found is &lt;a href="http://agilewebdevelopment.com/plugins/activerecord_base_without_table."&gt;http://agilewebdevelopment.com/plugins/activerecord_base_without_table.&lt;/a&gt;  It&amp;#8217;s kludgey, and to use it with Rails 2.x, you&amp;#8217;ll have to manually edit the file and change readmethods to generated_methods, but it&amp;#8217;s infinitely better than nothing.  I highly recommend using this plugin.&lt;/p&gt;


	&lt;p&gt;&lt;div class="property"&gt; category: &lt;a class="category_link" href="../list/Rant"&gt;Rant&lt;/a&gt;&lt;/div&gt;&lt;/p&gt;</description>
      <pubDate>Fri, 20 Feb 2009 09:14:55 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/TightCouplingInActiveRecordRant</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/TightCouplingInActiveRecordRant</link>
    </item>
    <item>
      <title>Rants</title>
      <description>&lt;p&gt;When you just need to vent&amp;#8230;&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/TightCouplingInActiveRecordRant"&gt;Tight Coupling in ActiveRecord&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;&lt;div class="property"&gt; category: &lt;a class="category_link" href="../list/Rant"&gt;Rant&lt;/a&gt;&lt;/div&gt;&lt;/p&gt;</description>
      <pubDate>Fri, 20 Feb 2009 09:12:51 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/Rants</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/Rants</link>
    </item>
    <item>
      <title>Best Practices</title>
      <description>&lt;h3&gt;Practices&lt;/h3&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/WriteAutomatedSpecs"&gt;Write Automated Specifications (AKA Tests)&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/UseMixinsToSeparateConcerns"&gt;Use Mixins to Separate Concerns&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;h3&gt;External Links&lt;/h3&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a href="http://www.rubyinside.com/21-ruby-tricks-902.html"&gt;21 Ruby Tricks&amp;#8230;&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;&lt;div class="property"&gt; category: &lt;a class="category_link" href="../list/Starting Points"&gt;Starting Points&lt;/a&gt;, &lt;a class="category_link" href="../list/Best Practices"&gt;Best Practices&lt;/a&gt;&lt;/div&gt;&lt;/p&gt;</description>
      <pubDate>Wed, 18 Feb 2009 07:59:30 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/Best+Practices</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/Best+Practices</link>
    </item>
    <item>
      <title>Use Mixins to Separate Concerns|</title>
      <description>&lt;p&gt;(Delete me)&lt;br /&gt;This content has been moved to &lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/UseMixinsToSeparateConcerns"&gt;Use Mixins To Separate Concerns&lt;/a&gt;&lt;/p&gt;</description>
      <pubDate>Wed, 18 Feb 2009 07:59:00 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/Use+Mixins+to+Separate+Concerns%7C</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/Use+Mixins+to+Separate+Concerns%7C</link>
    </item>
    <item>
      <title>Write Automated Specifications (AKA Tests)</title>
      <description>&lt;p&gt;(Delete me)&lt;br /&gt;This content has been moved to &lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/WriteAutomatedSpecs"&gt;WriteAutomatedSpecs&lt;/a&gt;&lt;/p&gt;</description>
      <pubDate>Wed, 18 Feb 2009 07:56:23 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/Write+Automated+Specifications+%28AKA+Tests%29</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/Write+Automated+Specifications+%28AKA+Tests%29</link>
    </item>
    <item>
      <title>Write Automated Specs</title>
      <description>&lt;p&gt;Yes, we&amp;#8217;re talking about writing &amp;#8220;Tests&amp;#8221;, but also following the new trend to refer primarily to &amp;#8220;Specifications&amp;#8221; instead, since that&amp;#8217;s really what we are trying to create.  We&amp;#8217;re writing code that acts as a specification for how we&amp;#8217;ll want to invoke some program functionality and how it is expected to behave under various conditions.&lt;/p&gt;


	&lt;p&gt;There are still good reasons to use tools such as Ruby&amp;#8217;s built-in Test::Unit in some cases rather than tools using the Specification/Behavior language of &lt;span class="newWikiWord"&gt;BehaviorDrivenDevelopment&lt;a href="http://ruby-practices.stevej.name/wiki/new/BDD"&gt;?&lt;/a&gt;&lt;/span&gt;, but regardless of the tool being used, think in terms of writing verifiable specifications.&lt;/p&gt;


	&lt;p&gt;More to come&amp;#8230;&lt;/p&gt;


	&lt;p&gt;&lt;div class="property"&gt; category: &lt;a class="category_link" href="../list/Best Practices"&gt;Best Practices&lt;/a&gt;&lt;/div&gt;&lt;/p&gt;</description>
      <pubDate>Wed, 18 Feb 2009 07:54:28 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/WriteAutomatedSpecs</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/WriteAutomatedSpecs</link>
    </item>
    <item>
      <title>Abstract Factory Via Module New</title>
      <description>&lt;p&gt;Just as in the &lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/AbstractFactoryViaAliasNew"&gt;Abstract Factory: alias &amp;lt;class&amp;gt;.new&lt;/a&gt; implementation, using this abstract factory implementation or refactoring to it should have no impact on the code that uses it.  Basically, instead of using the default &lt;code&gt;new&lt;/code&gt; method behavior of a named class to build instances of that class, we use the &lt;code&gt;new&lt;/code&gt; method of a named module to build arbitrary class instances for us.&lt;/p&gt;


	&lt;p&gt;Since, unlike in the &lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/AbstractFactoryViaAliasNew"&gt;Abstract Factory: alias &amp;lt;class&amp;gt;.new&lt;/a&gt;, we&amp;#8217;re defining &lt;code&gt;new&lt;/code&gt; for a module instead of redefining it for a class, we don&amp;#8217;t have to do any tricks with aliasing a class&amp;#8217; built-in &lt;code&gt;new&lt;/code&gt; method.&lt;/p&gt;


	&lt;h3&gt;A Trivial Example&lt;/h3&gt;


&lt;code&gt;&lt;pre&gt;
 module Foo

   module Base

     class Abstract
       attr_reader :name
     end

     def Base.new( name )
       concrete_class = const_get( name )
       concrete_class.new
     end

     class Bar &amp;lt; Abstract
       def initialize; @name='--BAR--'; end
     end

     class Baz &amp;lt; Abstract
       def initialize; @name='--BAZ--'; end
     end

   end

 end

# Try it out...
puts Foo::Base.new('Bar').name
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Output:&lt;/p&gt;


	&lt;pre&gt;&lt;code&gt;##BAR##&lt;/code&gt;&lt;/pre&gt;


	&lt;h3&gt;Variations:&lt;/h3&gt;


	&lt;h4&gt;Factory as a class rather than a module&lt;/h4&gt;


	&lt;p&gt;Since the factory module is not the thing we&amp;#8217;re making instances of, it doesn&amp;#8217;t really matter if it&amp;#8217;s a module or a class &amp;#8211; so we could make it a class.  That&amp;#8217;s misleading though, since the purpose of a class is to be something to have instances of, and we would never have an instance of that class.&lt;/p&gt;


	&lt;h3&gt;Useful Mixin Example With Unit Test Case&lt;/h3&gt;


	&lt;p&gt;Note that you&amp;#8217;ll need to unindent this code by one space to use it since the close of the &lt;span class="caps"&gt;EVAL&lt;/span&gt; here-document must be at the beginning of the line.&lt;/p&gt;


&lt;code&gt;
&lt;pre&gt;
 require 'test/unit'

 class NamedClassAbstractFactoryTest  &amp;lt; Test::Unit::TestCase

   def setup
     @factory = Module.new do |m|
       include NamedClassAbstractFactory
       m.module_eval &amp;lt;&amp;lt;EVAL
         class Foo; end
         class Bar; end
         constructs Foo, Bar
 EVAL
     end
   end

   def test_creates_foo_by_name
     obj = @factory.new( 'Foo' )
     assert_equal @factory::Foo, obj.class
   end

   def test_rejects_creation_by_unknown_name
     assert_raise( ArgumentError ) do
       obj = @factory.new( 'Baz' )
     end
   end

 end

 module NamedClassAbstractFactory

   def self.included(m)
     m.extend ClassMethods
     m.const_set :Constructable, {}
   end

   module ClassMethods

     def constructs( *classes )
       classes.each do |klass|
         name = klass.name.split('::').last
         self.const_get(:Constructable)[name] = klass
       end
     end

     def new( name )
       klass = self.const_get(:Constructable)[name]
       unknown_class( name ) unless klass
       klass.new
     end

    private

     def unknown_class( name )
       raise ArgumentError, "I don't know how to create a #{name}." 
     end

   end

 end
&lt;/pre&gt;&lt;br /&gt;&lt;/code&gt;

	&lt;p&gt;&lt;div class="property"&gt; category: &lt;a class="category_link" href="../list/Pattern Implementations"&gt;Pattern Implementations&lt;/a&gt;&lt;/div&gt;&lt;/p&gt;</description>
      <pubDate>Fri, 13 Feb 2009 21:55:13 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/AbstractFactoryViaModuleNew</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/AbstractFactoryViaModuleNew</link>
    </item>
    <item>
      <title>Abstract Factory Via Alias New</title>
      <description>&lt;p&gt;The ultimate in loose coupling is when the calling code doesn&amp;#8217;t have to know anything about the implementation.  If we simply follow the convention of using the &lt;code&gt;new&lt;/code&gt; class-method of the base class to create an instance, we completely isolate the decision of whether an abstract pattern is used from the calling code.  From the caller&amp;#8217;s perspective, just follow the usual conventions, and the right thing will happen.&lt;/p&gt;


	&lt;p&gt;The difficulty in trying to do this is that the &lt;code&gt;new&lt;/code&gt; implementation in the base class must call &lt;code&gt;new&lt;/code&gt; for a subclass for a new instance of that, but we&amp;#8217;ve overridden &lt;code&gt;new&lt;/code&gt; in the base class, so it has been overridden for the subclasses we&amp;#8217;re trying to instantiate as well.&lt;/p&gt;


	&lt;p&gt;A nice solution to this problem is to alias (rename) the original &lt;code&gt;new&lt;/code&gt; method before implementing our own.  We can then access the functionality normally performed by &lt;code&gt;new&lt;/code&gt; via its alias.&lt;/p&gt;


	&lt;h3&gt;A Trivial Example&lt;/h3&gt;


&lt;code&gt;&lt;pre&gt;
 module Foo

   class Base
     attr_reader :name

     class &amp;lt;&amp;lt; self
       alias :construct :new

       def new( name )
         Foo.const_get(name).construct
       end

     end

   end

   class Bar &amp;lt; Base
     def initialize; @name='##BAR##'; end
   end

   class Baz &amp;lt; Base
     def initialize; @name='##BAZ##'; end
   end

 end

 #Try it out...
 puts Foo::Base.new('Bar').name
&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;Output:&lt;/p&gt;


	&lt;pre&gt;&lt;code&gt;##BAR##&lt;/code&gt;&lt;/pre&gt;


	&lt;h3&gt;Variations:&lt;/h3&gt;


	&lt;h4&gt;Implement &lt;code&gt;inherited&lt;/code&gt; to &lt;code&gt;undef&lt;/code&gt; the &lt;code&gt;new&lt;/code&gt; method on subclasses.&lt;/h4&gt;


	&lt;p&gt;It&amp;#8217;s a bit odd that our concrete classes now inherit the &lt;code&gt;new&lt;/code&gt; method from the factory/base class.  That shouldn&amp;#8217;t be a big deal since the whole point is to use the base class as the factory and not refer to the subclasses directly.  Still, if that seems too smelly, you can use the &lt;code&gt;inherited&lt;/code&gt; callback to &lt;code&gt;undef&lt;/code&gt; the &lt;code&gt;new&lt;/code&gt; method in subclasses.  By this point, though, the &lt;a class="existingWikiWord" href="http://ruby-practices.stevej.name/wiki/show/AbstractFactoryViaModuleNew"&gt;Abstract Factory: &amp;lt;module&amp;gt;.new&lt;/a&gt; implementation starts to look much simpler.&lt;/p&gt;


	&lt;p&gt;&lt;div class="property"&gt; category: &lt;a class="category_link" href="../list/Pattern Implementations"&gt;Pattern Implementations&lt;/a&gt;&lt;/div&gt;&lt;/p&gt;</description>
      <pubDate>Fri, 13 Feb 2009 08:17:32 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/AbstractFactoryViaAliasNew</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/AbstractFactoryViaAliasNew</link>
    </item>
    <item>
      <title>Steve Jorgensen</title>
      <description>&lt;p&gt;&lt;a href="http://stevej.name"&gt;Steve Jorgensen&lt;/a&gt; is a software developer working in Ruby, Java, &lt;span class="caps"&gt;VB &lt;/span&gt;Classic, and &lt;span class="caps"&gt;VBA&lt;/span&gt;.&lt;/p&gt;</description>
      <pubDate>Wed, 11 Feb 2009 10:48:10 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/Steve+Jorgensen</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/Steve+Jorgensen</link>
    </item>
    <item>
      <title>Design Pattern References</title>
      <description>&lt;h1&gt;Design Pattern References&lt;/h1&gt;


	&lt;p&gt;Here are some external references to sites discussing design patterns in general (not Ruby-specific).&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;a href="http://en.wikipedia.org/wiki/Design_pattern_(computer_science)"&gt;Wikipedia entry&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://c2.com/cgi/wiki?DesignPatterns"&gt;Design patterns at c2.com&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;</description>
      <pubDate>Wed, 11 Feb 2009 10:09:06 Z</pubDate>
      <guid>http://ruby-practices.stevej.name/wiki/show/Design+Pattern+References</guid>
      <link>http://ruby-practices.stevej.name/wiki/show/Design+Pattern+References</link>
    </item>
  </channel>
</rss>

