<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <title>Upstate Ruby Brigade - Home</title>
  <id>tag:upstaterb.org,2008:mephisto/</id>
  <generator uri="http://mephistoblog.com" version="0.8.0">Mephisto Drax</generator>
  <link href="http://upstaterb.org/feed/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="http://upstaterb.org/" rel="alternate" type="text/html"/>
  <updated>2008-07-18T13:51:55Z</updated>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>ryan</name>
    </author>
    <id>tag:upstaterb.org,2008-07-12:47</id>
    <published>2008-07-12T02:56:00Z</published>
    <updated>2008-07-18T13:51:55Z</updated>
    <category term="Meetings"/>
    <category term="rails2.1"/>
    <link href="http://upstaterb.org/2008/7/12/july-meeting-tues-7-22-12pm" rel="alternate" type="text/html"/>
    <title>July Meeting - Tues 7/22 @ 12pm</title>
<content type="html">
            &lt;h3&gt;&lt;em&gt;UPDATE&lt;/em&gt;: FREE LUNCH! Lunch will be provided by Tek Systems. See below for details.&lt;/h3&gt;

&lt;h2&gt;Topic: Rails 2.1 Roundtable&lt;/h2&gt;

&lt;p&gt;With the release of Rails 2.1, there are a number of new tools at developers disposal. &lt;a href=&quot;http://weblog.sourcescape.com&quot;&gt;Ryan&lt;/a&gt; will walk through an overview of new tip &amp;amp; tricks so you too can be on the cutting edge of Rails development again.&lt;/p&gt;

&lt;p&gt;Doors are open at 11:45am so we can chat before the presentation begins at 12:00pm. If you&#8217;re pressed for time at lunch, feel free to come right at 12:00pm.&lt;/p&gt;

&lt;h2&gt;Location&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://www.immedion.com/&quot;&gt;Immedion&lt;/a&gt; will be graciously hosting our group. &lt;a href=&quot;http://upstaterb.org/2008/3/7/meeting-directions&quot;&gt;Click here for directions&lt;/a&gt;. &lt;/p&gt;

&lt;h2&gt;Lunch&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;We WILL have a sponsored lunch. I&#8217;ll need a headcount by Monday. Please let us know through the mailing list. Thanks!&lt;/strong&gt;&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>andy</name>
    </author>
    <id>tag:upstaterb.org,2008-06-26:44</id>
    <published>2008-06-26T16:30:00Z</published>
    <updated>2008-06-26T16:15:05Z</updated>
    <category term="andy"/>
    <category term="named_scope"/>
    <category term="rails2.1"/>
    <link href="http://upstaterb.org/2008/6/26/problem-with-named_scope-and-include" rel="alternate" type="text/html"/>
    <title>Problem with named_scope and :include?</title>
<content type="html">
            &lt;p&gt;Recently I've been using the great Rails 2.1 addition called named_scope to help simplify the process of building queries with meaningful names.  Certainly you could do something similar by creating a custom method, but &lt;a href=&quot;http://www.upstaterb.org/2008/6/2/new-in-rails-2-1-named_scope&quot;&gt;as I wrote earlier&lt;/a&gt;, the advantage of named_scope is that the scopes are composable: you can chain them together to build ever more powerful queries.&lt;/p&gt;

&lt;p&gt;That's why I've been &lt;em&gt;really&lt;/em&gt; frustrated trying to get named scopes to work with the :include option.  In one scenario I have been trying to sort a collection by a field that exists in an included table.  If I were doing freight-forwarding the models involved look something like this.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Customer &amp;lt; ActiveRecord::Base
  has_many :product_offerings
  has_many :products, :through=&amp;gt;:product_offerings
end

class Product
  has_many :product_offerings
end

class ProductOffering
  belongs_to :customer
  belongs_to :product

  named_scope :by_name, :include=&amp;gt;:product, :order=&amp;gt;:name
  named_scope :for_customers, lambda{|customer_ids| {:conditions=&amp;gt;{:customer_id=&amp;gt;customer_ids}}}
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The objective I have in mind is to build a named_scope that allows me to list all the products for a particular customer alphabetically by the name of the product so each customer can check their inventory.  In the day and age where holding companies are involved an individual user may be authorized for several companies and thus want to be able to get a unified inventory list for all the companies for whom he works.  That's where the second named_scope comes into play.  I'd like to be able to do this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;# all the product offerings listed by product name
ProductOffering.by_name

# all the product offerings for a set of customers
ProductOffering.for_customers([1, 2, 3])

# all the product offerings by name for a user's companies
ProductOffering.by_name.for_customers(@current_user.customer_ids)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But it doesn't work.  For some reason the :include option seems to get dropped and I end up getting SQL errors reporting an unknown column name.  I've found one stray comment that suggests that you may be able to fix the issue by adding the conditions necessary to make the SQL join work.  That is we could expand the named_scope to something like&lt;/p&gt;

&amp;lt;filter:jscode&gt;
  named_scope :by_name, :include=&gt;:product, :order=&gt;:name, :conditions=&gt;[&quot;products.id = product_offerings.product_id&quot;]
&amp;lt;filter:jscode&gt;

&lt;p&gt;That's ugly.  Really ugly.  It also pushes perilously close to letting ProductOffering peek into Product too much.  If you begin to go that route be careful because you'll be on the slippery slope of a brittle solution that won't survive refactoring.&lt;/p&gt;

&lt;p&gt;The simple solution is to bypass :include in favor of :join.  I don't understand why :join works more reliably but I'm sure the answer is down there in the source code if you want to dig around.  I suspect that the answer lies in the way that Rails 2.1 breaks joins into two distinct fetches now in order to reduce the cost of spinning up redundant ActiveRecord instances (see&lt;a href=&quot;http://giantrobots.thoughtbot.com/2008/6/19/gotchas-when-upgrading-to-rails-2-1&quot;&gt; the Relationship Optimised Eager Loading discussion.&lt;/a&gt;).  Whatever the case, the workable, concise solution looks like this:&lt;/p&gt;

&amp;lt;filter:jscode&gt;
  named_scope :by_name, :joins=&gt;:product, :order=&gt;:name
&amp;lt;filter:jscode&gt;

&lt;p&gt;If you already need to include conditions on the join table you can probably continue along as you normally would.  In this situation the only requirement on the join table is that the IDs match so I prefer the concise solution.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>ryan</name>
    </author>
    <id>tag:upstaterb.org,2008-06-19:42</id>
    <published>2008-06-19T18:10:00Z</published>
    <updated>2008-06-19T18:12:55Z</updated>
    <category term="Meetings"/>
    <link href="http://upstaterb.org/2008/6/19/june-meeting-cancelled" rel="alternate" type="text/html"/>
    <title>June Meeting Cancelled</title>
<content type="html">
            &lt;p&gt;Just a quick note to let you know that the June meeting has been canceled. Keep a look out for announcements for some geek dinners this summer.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>andy</name>
    </author>
    <id>tag:upstaterb.org,2008-06-03:40</id>
    <published>2008-06-03T02:00:00Z</published>
    <updated>2008-07-29T13:54:14Z</updated>
    <category term="Rails"/>
    <category term="andy"/>
    <category term="rails2.1"/>
    <link href="http://upstaterb.org/2008/6/3/new-in-rails-2-1-timestamped-migrations" rel="alternate" type="text/html"/>
    <title>New in Rails 2.1: Timestamped migrations</title>
<content type="html">
            &lt;h2&gt;What was wrong with migrations?&lt;/h2&gt;
&lt;p&gt;If you've been part of any development team that was larger than the &quot;Army of One&quot; you've probably run into an issue with migrations.  It's happened to me a few times: one member of the teams goes head-down on some problem and it takes longer than expected.  Not wanting to check in 'broken'' code the patch builds up for a while... and so do the migrations to fix db issues.  Finally ready, the change gets checked in and ... poof... What worked no longer works.  Why? &lt;/p&gt;
&lt;p&gt; While Mr. Fix-It was head down the trunk was updated with other migrations.  But these migrations had overlapping numbers so when they merged into the code base it was unpredictable which ones would be run on any given system.  To be clear, the migrations will be run in a very definitie order.  They're run in alphanumeric order, but only one migration of a specific 'version' will be executed.  As a result, which migrations are run on your system depends on how many you'd already checked out and run and the alphabetical naming of each script.  Now it's up to you and your team to rename all the migrations, backing them out one by one and adding them back to make sure all the database changes are applied appropriately.  Yikes!&lt;/p&gt;
&lt;h2&gt;Enter Sandman&lt;/h2&gt;
&lt;p&gt;Disclaimer: I've only heard 'Sandman' when certain closers enter baseball games but I thought someone would appreciate the reference&lt;/p&gt;
&lt;p&gt;The new timestamped migrations may put all these issues to rest.  Instead of prefixing the migrations with 001, 002, 003, etc the prefix will now be a timestamp.  So, the result of running a 'script/generate scaffod MyObject attribute1:string attribute2:integer' will be a file with a name like &lt;em&gt;20080601214508_create_my_object&lt;/em&gt;.  The likelihood that you and a teammate create a migration at the exact same time is pretty small so the 'level collisions' are almost surely a thing of the past.&lt;/p&gt;
&lt;h2&gt;Tracking revisions, not the version&lt;/h2&gt;
&lt;p&gt;Even better, though, is that the schema_info table will now track &lt;em&gt;revisions&lt;/em&gt;, not only the latest version.  That is, every migration that is run via &lt;strong&gt;rake db:migrate&lt;/strong&gt; will be recorded in the database.  As a result, whenever Mr. Fix-It decides to enlighten the rest of the team with his update, a &lt;strong&gt;rake db:migrate&lt;/strong&gt; will be able to identify the individual migrations that have not been run whether they were on Mr. Fix-It's machine (when he finally updates from trunk/master) or on a teammates' machine (when the patch is loaded).&lt;/p&gt;
&lt;p&gt;Even better, there are new &lt;strong&gt;rake db:migrate:up&lt;/strong&gt; and &lt;strong&gt;rake db:migrate:down&lt;/strong&gt; commands.  These commands accept an individual migration 'version' (the time stamp) and either run it (up) or back it out (down).  Remember that table that you created and decided you'd overengineered?  Now it's a lot easier to back that one out.
&lt;h2&gt;Could it get even better?&lt;/h2&gt;
&lt;p&gt;Yes, it could get better.  Those of you who've read &lt;em&gt;The Rails Way&lt;/em&gt; (Obie Fernandez, Addison-Wesley Professional Series, 2007) may have come across a recommendation to accumulate migration changes until they are pushed to production.  That is, rather than create three migrations for a table and some additional fields while the table is in development, there is a recommendation to have one create script that gets updated until it's pushed to production.  I've tried this on a couple of apps and really liked the approach because it cuts down on the 'noise' in the migration collections.  I'm willing to accept the argument that migrations are not really necessary for tracking database changes until they change something beyond development.&lt;/p&gt;
&lt;p&gt;What could be even better that the current implementation of the timestamped migration would be if it could detect these changes in the migration files.  It should be possible to check the creation and update times of the files to see if they've been updated and then validate the updated time in the migrations db.  This particular idea has some drawbacks, particularly if a production migration were ever touched accidentally.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>andy</name>
    </author>
    <id>tag:upstaterb.org,2008-06-02:39</id>
    <published>2008-06-02T02:30:00Z</published>
    <updated>2008-07-29T13:54:50Z</updated>
    <category term="Rails"/>
    <category term="andy"/>
    <category term="rails2.1"/>
    <link href="http://upstaterb.org/2008/6/2/new-in-rails-2-1-named_scope" rel="alternate" type="text/html"/>
    <title>New in Rails 2.1: named_scope</title>
<content type="html">
            &lt;h2&gt;Rails 2.1 Released&lt;/h2&gt;
&lt;p&gt;If you haven't heard, the release of Rails 2.1 was announced during core member Jeremy Kemper's keynote Saturday morning (but it didn't actually get released until around 2am the next morning).  &lt;/p&gt;

&lt;h2&gt;named_scope&lt;/h2&gt;
&lt;p&gt;One of my favorite additions to the framework is the absorption of the has_finder plugin into the framework.    If you've used has_finder in the past the only thing you'll need to do in order to 'go native' with it in your application is replace the 'has_finder' invocations with 'named_scope'.  If you are not familiar with has_finder, it gives you the ability to declare custom finders in a concise, semantically meaningful way.  For example:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Task &amp;lt; ActiveRecord::Base
  named_scope :incomplete, :conditions=&amp;gt;{:completed_at=&amp;gt;nil}
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the Grade class above, we've used named scope to add a class-level finder called 'incomplete' that will perform the equivalent of this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;Task.find(:all, :conditions=&amp;gt;{:completed_at=&amp;gt;nil})&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Great, so now I can write Task.incomplete and get a list of the incomplete tasks.  But so what?  I could have written a class-level method myself.  Is this anything more than syntactic sugar?  Yes!&lt;/p&gt;

&lt;h2&gt;named_scopes can combine&lt;/h2&gt;
&lt;p&gt;The &lt;em&gt;real&lt;/em&gt; beauty of named scopes is that they chain together.  Well crafted named_scopes are fine-grained pieces of find parameters that have clear purposes and meaninful names.  Consider these:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Task &amp;lt; ActiveRecord::Base
  named_scope :incomplete, :conditions=&amp;gt;{:completed_at=&amp;gt;nil}
  named_scope :past_due, lambda{ {:conditions=&amp;gt;['due_on &amp;lt; ?', Date.today]}}
  named_scope :due_today, lambda{ {:conditions=&amp;gt;['due_on = ?', Date.today]}}
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;
&lt;b&gt;Task.incomplete.past_due&lt;/b&gt; is the same as &lt;b&gt;Task.find(:all, :conditions=&gt;['completed_at is NULL and due_on &amp;lt; ?', Date.today]&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;Sweet.  The chaining of the named_scopes means that you can create really nice 'sentences' in your Rails code that is clear and easy to read.  &lt;/p&gt;

&lt;h2&gt;named_scopes play nicely with association proxies&lt;/h2&gt;
&lt;p&gt;Even better, the named_scopes work through association proxies as well.  Without getting into the details too much, assume that your User class has_many Tasks.  Now, your boss wants you to help him through a commons scenario.  &quot;Ryan, how can I figure out how many tasks that slacker Chris has let slide.  Easy.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;@chris = User.find_by_name('chris')
@chris.tasks.incomplete.past_due&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the first place I used this, the code became a lot easier to read.  I added a named_scope that at first did not make a lot of sense: it added a model-related scope to the find.  In this case it helped the code because I was normally accessing the data through another 'owner' and this named_scope helped me chain in finer focus.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;@grades ||= @student.unreported_grades.find(:all, :conditions=&amp;gt;{:subject_id=&amp;gt;params[:subject_id]})
    @grades ||= @student.grades.unreported.for_subject(params[:subject_id])&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The commented code is the original version that used a (now deprecated) class-level method.  Passing the find conditions there worked but it was a little ugly.  The named_scope version is both clearer and easier to maintian.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>ryan</name>
    </author>
    <id>tag:upstaterb.org,2008-04-29:25</id>
    <published>2008-04-29T20:32:00Z</published>
    <updated>2008-04-29T20:33:28Z</updated>
    <category term="Meetings"/>
    <category term="haml"/>
    <category term="markup"/>
    <category term="meeting"/>
    <category term="sass"/>
    <link href="http://upstaterb.org/2008/4/29/next-meeting-may-27-11-45am" rel="alternate" type="text/html"/>
    <title>Next Meeting: May 27 @ 11:45am</title>
<content type="html">
            &lt;h2&gt;Topic: Do you HAML and SASS?&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://sourcescape.com&quot;&gt;Ryan&lt;/a&gt; will be your guide through the wonderful world that is &lt;a href=&quot;http://haml.hamptoncatlin.com/&quot;&gt;HAML &amp;amp; SASS&lt;/a&gt;. Be prepared to take your markup to heights not seen since Chris &#8220;experimented&#8221; with mushrooms back in college. &lt;/p&gt;

&lt;p&gt;The start time has moved up to 11:45am so we can chat before the presentation begins at 12:00pm. If you&#8217;re pressed for time at lunch, feel free to come right at 12:00pm.&lt;/p&gt;

&lt;h2&gt;Location&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://www.immedion.com/&quot;&gt;Immedion&lt;/a&gt; will be graciously hosting us again. &lt;a href=&quot;http://upstaterb.org/2008/3/7/meeting-directions&quot;&gt;Click here for directions&lt;/a&gt;. &lt;/p&gt;

&lt;h2&gt;Lunch&lt;/h2&gt;

&lt;p&gt;Lunch will be on your own this month. Feel free to pick something up and bring it to the meeting or just brown bag it. &lt;strong&gt;Please add a comment if you&#8217;d like us to start providing lunch (for a nominal fee).&lt;/strong&gt;&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>andy</name>
    </author>
    <id>tag:upstaterb.org,2008-04-24:24</id>
    <published>2008-04-24T20:30:00Z</published>
    <updated>2008-07-29T13:55:13Z</updated>
    <category term="Rails"/>
    <category term="active_resource"/>
    <category term="andy"/>
    <category term="rails"/>
    <link href="http://upstaterb.org/2008/4/24/5-tips-for-activeresource" rel="alternate" type="text/html"/>
    <title>5 Tips for ActiveResource</title>
<content type="html">
            &lt;p&gt;The first couple of tips have an indrect impact on ActiveResource.  Still, they are worth keeping in mind because they simplify the data with which ActiveResource deals.&lt;/p&gt;
&lt;h2&gt;Tip 1: Use delegate and :method for encapsulation&lt;/h2&gt;
&lt;p&gt;If your crash course in Ruby involved reading the Agile book, then the delegate method may be new to you.  Delegate is a class-level command that allows you to pass certain method calls on to an associated model.  For example, if you have a highly-factored address book you might have a pair of models like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Address &amp;lt; ActiveRecord::Base
  belongs_to :zip_code
end

class ZipCode &amp;lt; ActiveRecord::Base
  has_many :addresses
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That's a model with some theoretical purity... but in practice it's cumbersome.  You &lt;em&gt;really&lt;/em&gt; want to deal with an address that has all the information you'd like to render (street, city, state, zip) in on model.  Atleast it should &lt;em&gt;feel&lt;/em&gt; that way.  That's precisely where the delegate command comes into play.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Address &amp;lt; ActiveRecord::Base
  belongs_to :zip_code
  delegate :city, :state, :zip, :to=&amp;gt;:zip_code
  delegate 'city=', 'state=', 'zip=', :to=&amp;gt;:zip_code
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Modeled as shown above you can ask an address for it's city and the address will pass the request on to the zip_code object to which it belongs, retrieve the answer, and return it to you.  (It's taking advantage of the fact that Rails is doing some method_missing magic to provide getters and setters for your attributes).  That level of encapsulation will become increasingly important when you begin to use ActiveResource heavily.  In many cases you may want to return only a few fields from an associated model and, as in the example above, you do not want or need to reveal how you've organized your data to the outside world.&lt;/p&gt;
&lt;p&gt;The final piece to the puzzle with respect to ActiveResource will be making sure you use the :method parameter when you serialize the delegating object to xml.&lt;/p&gt;

&lt;h3&gt;addresses_controler.rb&lt;/h3&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;...
def show
  @address = Address.find(params[:id], :include=&amp;gt;:zip_code)
  respond_to do |format|
    format.html # show.html.erb
    format.xml  { render :xml =&amp;gt; @address.to_xml(:methods=&amp;gt;[:city, :state, :zip])
  end
end
...&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As shown, the call to @address.to_xml tries to include the results of calling the city, state, and zip getter methods on address.  The delegate command causes the Address object to pass that request on to the association ZipCode object and the results are returned and placed into the xml envelope as if they were attributes of the address (which they are, indirectly).  The application that's consuming all this through ActiveResource remains blissfully unaware of your modeling nirvana.  It simply receives some nicely formatted xml along the lines of this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;xml&quot;&gt;&amp;lt;home-address&amp;gt;
  &amp;lt;id type=&amp;quot;integer&amp;quot;&amp;gt;1&amp;lt;/id&amp;gt;
  &amp;lt;street&amp;gt;123 Main St.&amp;lt;/street&amp;gt;
  &amp;lt;city&amp;gt;Anytown&amp;lt;/city&amp;gt;
  &amp;lt;state&amp;gt;XX&amp;lt;/state&amp;gt;
  &amp;lt;zip&amp;gt;12345&amp;lt;/zip&amp;gt;
&amp;lt;/home-address&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Tip 2: Clean up the delgation you just learned to keep the code clean and clear&lt;/h2&gt;
&lt;p&gt;If you start maximizing your use of delegate your code can get untidy especially since delegate introduces some duplication when you're dealing with attribute accessors.  If we keep in mind that class declarations are &lt;em&gt;still Ruby scripts&lt;/em&gt; then we can clean the attribute accessor delegation pretty easily while making the intent very clear.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Address &amp;lt; ActiveRecord::Base
  belongs_to :zip_code
  [:city, :state, :zip].each do |delegated_accessor|
    delegate &amp;quot;#{delegated_accessor}&amp;quot;, &amp;quot;#{delegated_accessor}=&amp;quot;, :to=&amp;gt;:zip_code
  end
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;On to some tips with more direct bearing on ActiveResource itself.&lt;/p&gt;

&lt;h2&gt;Tip 3: Use AppConfig to get your site information out of the class file!&lt;/h2&gt;
&lt;p&gt;The Core did a great job modeling ActiceResource along the lines of ActiveRecord so that using ActiveResource feels very natural to any Rails programmer.  But it's also left me stumped as to why there is no equivalent to /config/databases.yml.  I suppose that in some cases you will be using a well-known, established, public REST interface but I'm finding ActiveResource to be a very natural way to develop 'sub-applications' that can be shared to create a larger application.  Because of that I need to be able to have different site information for development, test, and production.  Clearly some configuration is needed.&lt;/p&gt;
&lt;p&gt;Even though I shudder at the thoughts that a name like 'AppConfig' brings to mind, it's a great part of the solution to this problem.  If you're not familiar with it, AppConfig allows you to provide a yaml config files for global (/config/app_config.yml) and environment-specific (e.g., /config/environments/development.yml) configuration.  The plugin reads these config files, merges inforamtion as necessary, and provides all the options as class-level attributes of the AppConfig class.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;sites:
  addressbook: http://localhost:3001
  financials: 
    url: http://localhost:3002
    username: money
    password: talks&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The yaml above shows two different types of configuration that would be useful for ActiveResource, organized together under a 'sites' attribute.  The first one (addressbook) is the way I started before I ran into an application that needed http basic authentication.  The site info consists only of the url.  The second one (financials) came out of the latter need.  A quick extension of ActiveResource causes these to spring into action.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class ActiveResource::Base
  protected
  def self.establish_site_connection(site_id)
    raise(ArgumentError, &amp;quot;#{site_id} is not defined for #{RAILS_ENV}&amp;quot;) unless AppConfig.sites.respond_to?(site_id)
    site_info = AppConfig.sites.send(site_id)
    return site_info.respond_to?(:url) ? site_with_basic_auth_info(site_info) : site_info
  end
  
  def self.site_with_basic_auth_info(site_info)
    site = URI.parse(site_info.url)
    site.userinfo = &amp;quot;#{site_info.username}:#{site_info.password}&amp;quot;
    return site.to_s
  end
end&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I've been dropping the code above into /lib/core_ext/active_resource_extension.rb.  The first method (establish_site_connection) is meant to emulate ActiveRecord::Base#establish_database_connection.  It accepts a site id in the form of a symbol or string and retrieves the site configuration matching that id.  If that site info is already a simple string, that string is returned unmodified.  If the site_info is further broken down into the url, user name and password for http basic authentication then that is handed off to the site_with_basic_auth_info method to build up a simple string.&lt;/p&gt;
&lt;p&gt;It's true that the http basic authentication credentials could be written into the url.  In fact, that's exactly what the site_with_basic_auth_info does.  If that's the case, then why add the username and password to the config file?&lt;/p&gt;

&lt;h2&gt;Tip 4: Share your site AppConfig settings between your applications&lt;/h2&gt;
&lt;p&gt;When you have the fortunate advantage of controlling both your ActiveResource-based application and your ActiveRecord-based application you can share the configuration information between the applications.  Specifically, you can share the username and password information used for http basic authentication so that both sides can be externally configured... and reconfigured.  By sharing the configuration files and including the use of AppConfig in the source application for the ActiveResource your http basic authentication will be as simple as&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def basically_authenticated(user, password)
  user==AppConfig.sites.financials.username &amp;amp;&amp;amp; password==AppConfig.sites.financials.password
end&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What makes this even more compelling is that AppConfig (as anything leaning on yaml) allows you to use ERb in your configuration files.  Why is that significant?&lt;/p&gt;

&lt;h2&gt;Tip 5: Use Embedded Ruby in your configuration files to automatically change your user/password&lt;/h2&gt;
&lt;p&gt;Clearly with http basic authentication you will want to go the extra step of passing through a secure connection, but if you're too tired to add an 's' to your http, then you'll want to change your clear-text password.  Often.  Embedding Ruby might be just the trick because you could share a single algorithm between your applications that would change the password for you.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;sites:
  addressbook: http://localhost:3001
  financials: 
    url: http://localhost:3002
    username: &amp;lt;%= %w{money cash penny moulah dineiros pennywise poundfoolish}[Date.today.wday] %&amp;gt;
    password: &amp;lt;%= Digest::SHA1.hexdigest(&amp;quot;#{Date.today.to_s}---financials&amp;quot;) %&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There is a potential pitfall here.  With this type of approach -- shifting the user/password each day -- the application servers will have to be kept in step.  A reboot on one machine will require a reboot or restart on the other to make sure the applications share the same username/password since the AppConfig object will be re-loaded when the webserver starts.  Pick the scheme that works best for you.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>andy</name>
    </author>
    <id>tag:upstaterb.org,2008-04-22:23</id>
    <published>2008-04-22T20:30:00Z</published>
    <updated>2008-07-29T13:55:43Z</updated>
    <category term="Rails"/>
    <category term="active_resource"/>
    <category term="andy"/>
    <category term="rails"/>
    <link href="http://upstaterb.org/2008/4/22/why-assign-site-in-activeresource" rel="alternate" type="text/html"/>
    <title>Why assign site in ActiveResource?</title>
<content type="html">
            &lt;p&gt;ActiveResource is a great tool for helping your business keep not only its business logic DRY, but even keep its business applications dry.  If you're not familiar with ActiveResource, think of &lt;a href=&quot;http://www.martinfowler.com/eaaCatalog/activeRecord.html&quot;&gt;ActiveRecord&lt;/a&gt; using an internet-based datastore.  It's a bit more complicated than that but you can do all the basic CRUD methods, custom methods, etc &lt;/p&gt;
&lt;p&gt;The advantage that ActiveResource brings, though, is that you only need to create the object once.  Ever.  Used effectively, you don't need to create an object in one project that you import or somehow reuse in another.  You create a small, targetted application and share the application with other applications.  For example, you could create an accounting engine that deals with ledgers and accounts and journals and expose the RESTful HTTP interface to higher level apps that simply consume the Journals and Ledgers and Accounts using ActiveResource.  Within a single company it might be the ultimate in DRY.&lt;/p&gt;
&lt;p&gt;For Rails developers, ActiveResource is very clearly modeled on ActiveRecord.  If you've gotten used to one set of methods you should almost seamlessly be used to the other.  With one painful exception: setting the site in the class.  I honestly cannot understand why there is no configuration yaml equivalent to database.yml for ActiveResource.  Maybe it was unnecessary since the creators already had some RESTful applications with which to work.  Whatever the case, it's a real pain in the neck.&lt;/p&gt;
&lt;p&gt;In an attempt to keep the ActiveRecord-like API going, I've come up with the following code that I've been dropping in /lib/core_ext/active_resource.rb&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;require 'yaml'
class ActiveResource::Base
  protected
  def self.establish_site_connection(site_id)
    site_yaml = File.new(File.join(RAILS_ROOT, 'config', 'sites.yml'))
    environment_configurations = YAML.load site_yaml
    site_configurations = environment_configurations[RAILS_ENV]
    return site_configurations[site_id.to_s]
  end
end&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The code is supposed to emulate ActiveRecord.establish_database_connection.  As implemented above it will add an establish_site_connection method to your ActiveResource class that will read a sites.yml file in your /config folder.  sites.yml is structured similarly to database.yml -- you have entries for each environment (development, test, production, etc) along with site names and urls for each site.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;development:
  activity_center: http://localhost:3002/
  church_member: http://localhost:3001/

test:
  activity_center: http://testy:3002/
  church_member: http://testy:3001/&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With such a configuration file, of course, you have a few luxuries.  First, you can use different sites while running in different environments.  This might make it easier, for example, to create mocks for testing ActiveResource objects.  Second, you can more quickly adapt to external changes (e.g., remote resource down or relocated) since it's just a yaml change and not a source code change.&lt;/p&gt;
&lt;p&gt;I've typically gone one step further with the ActiveResource hack.  As alluded to above, I have sites split into separate sub-applications each responsible for part of the end solution.  As a result I have a whole family of ActiveResources that use one source application.  For this reason I have emulated the multiple database solution for Rails with the following for ActiveResource.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;require File.join(RAILS_ROOT, 'lib', 'core_ext', 'active_resource_extension')
class ActivityCenterResource &amp;lt; ActiveResource::Base
  # see /lib/core_ext/active_resource_extensison.rb
  self.site = self.establish_site_connection(:activity_center)
end

class ActivityCenter &amp;lt; ActivityCenterResource
  ...
end&lt;/code&gt;&lt;/pre&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>ryan</name>
    </author>
    <id>tag:upstaterb.org,2008-04-16:22</id>
    <published>2008-04-16T13:15:00Z</published>
    <updated>2008-04-16T14:49:45Z</updated>
    <category term="Meetings"/>
    <category term="active_resource"/>
    <category term="meetings"/>
    <link href="http://upstaterb.org/2008/4/16/next-meeting-tues-apr-22-11-45am" rel="alternate" type="text/html"/>
    <title>Next Meeting: Tues, Apr 22 @ 11:45am</title>
<content type="html">
            &lt;h2&gt;Topic: Introduction to ActiveResource&lt;/h2&gt;

&lt;p&gt;Andy Vanasse will be presenting on ActiveResource, the Rails 2.0 pattern for consuming your RESTful application&#8230; in another application.  We&#8217;ll walk through the basics of ActiveResource, discuss ways it could be used to solve application needs, and kick around some practical tips and tricks picked up through an application that relies heavily on ActiveResource.&lt;/p&gt;

&lt;p&gt;The start time has moved up to 11:45am so we can chat before the presentation begins at 12:00pm. If you&#8217;re pressed for time at lunch, feel free to come right at 12:00pm.&lt;/p&gt;

&lt;h2&gt;Location&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://www.immedion.com/&quot;&gt;Immedion&lt;/a&gt; will be graciously hosting us again. &lt;a href=&quot;http://upstaterb.org/2008/3/7/meeting-directions&quot;&gt;Click here for directions&lt;/a&gt;. &lt;/p&gt;

&lt;h2&gt;Lunch&lt;/h2&gt;

&lt;p&gt;Lunch will be on your own this month. Feel free to pick something up and bring it to the meeting or just brown bag it.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>ryan</name>
    </author>
    <id>tag:upstaterb.org,2008-03-18:19</id>
    <published>2008-03-18T13:23:00Z</published>
    <updated>2008-03-18T13:24:08Z</updated>
    <category term="Meetings"/>
    <category term="meeting"/>
    <category term="rpec"/>
    <link href="http://upstaterb.org/2008/3/18/next-meeting-march-25-12pm" rel="alternate" type="text/html"/>
    <title>Next Meeting: March 25 @ 12pm</title>
<content type="html">
            &lt;h2&gt;Topic: Introduction to RSpec&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://weblog.sourcescape.com&quot;&gt;Ryan Wood&lt;/a&gt; will be presenting on &lt;a href=&quot;http://rspec.info&quot;&gt;RSpec&lt;/a&gt;, a Ruby &lt;acronym title=&quot;Domain Specific Language&quot;&gt;DSL&lt;/acronym&gt; for &lt;acronym title=&quot;Behavior Driven Development&quot;&gt;BDD&lt;/acronym&gt; (enough &lt;acronym title=&quot;Three Letter Acronym&quot;&gt;TLA&lt;/acronym&gt;s?) . In other words, &lt;em&gt;it&#8217;s that hot new testing framework that&#8217;s causing  all the cool kids to drop Test::Unit like last year&#8217;s prom queen and swoon with blind adoration&lt;/em&gt;. Actually, it is pretty cool. If you haven&#8217;t heard of it, come and find out how you to can be one of the cool kids too!&lt;/p&gt;

&lt;h2&gt;Location&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://www.immedion.com/&quot;&gt;Immedion&lt;/a&gt; will be graciously hosting us again. &lt;a href=&quot;http://upstaterb.org/2008/3/7/meeting-directions&quot;&gt;Click here for directions&lt;/a&gt;. &lt;/p&gt;

&lt;h2&gt;Lunch&lt;/h2&gt;

&lt;p&gt;Lunch will be on your own this month. Feel free to pick something up and bring it to the meeting or just brown bag it.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>andy</name>
    </author>
    <id>tag:upstaterb.org,2008-03-17:18</id>
    <published>2008-03-17T21:30:00Z</published>
    <updated>2008-07-29T13:56:02Z</updated>
    <category term="Rails"/>
    <category term="andy"/>
    <category term="plugins"/>
    <category term="rails"/>
    <category term="sti"/>
    <link href="http://upstaterb.org/2008/3/17/sti-factory" rel="alternate" type="text/html"/>
    <title>STI Factory</title>
<content type="html">
            &lt;h2&gt;Single Table Inheritance&lt;/h2&gt;
&lt;p&gt;One of the abstractions that I really like in Rails is its implementation of Single Table Inheritance (STI).  If you're not familiar with STI, it is a simple design pattern in which you model an inheritance hierarchy in a single database table (Martin Fowler does it more justice &lt;a href=&quot;http://martinfowler.com/eaaCatalog/singleTableInheritance.html&quot;&gt;here&lt;/a&gt;).  Since ActiveRecord, Rails' primary domain modeling base class, is also db-centric the marriage of the two is fairly straight forward: include a column called 'type' in your database table and you're done.  Simple.&lt;/p&gt;

&lt;h2&gt;But type is a real headache&lt;/h2&gt;
&lt;p&gt;In practice it turns out that it's not always so simple.  In a number of applications that I've worked on we like to put the user in the driver's seat by allowing them to select the subtype they are going to create.  For example, assume that we start with a domain modeling different types of vehicles.  Without getting into all the attributes that might distinguish the vehicles, the class model might look something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Vehicle &amp;lt; ActiveRecord::Base
  def self.inheritance_column
    'vehicle_type' # we'll see why in a bit...
  end
end

class Car &amp;lt; Vehicle
end

class Truck &amp;lt; Vehicle
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What I'd really like to do is give the user a select and let them pick either 'Car' or 'Truck'.  That in itself is &lt;em&gt;should&lt;/em&gt; not be too difficult.  There is one little gotcha: type is a reserved word in Ruby.  If you try to use a select or select_tag helper Rails (Ruby) will complain with an error that will probably leave you scratching your head for a while.  The simple way to avoid this problem is shown above.  You override the class-level inheritance column method and return the name of the column that you will use to discriminate among classes in the inheritance hierarchy.  In this case we're using the column 'vehicle_type' to hold the name of the subclass.&lt;/p&gt;

&lt;p&gt;Things get trickier when you get back to the controller.  It turns out that Rails musters up some righteous indignation about any attempt to change the class.  To see what I mean, let's simulate what you might see back in the VehiclesController if you let the user request a Porche Cayenne...&lt;p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;params = HashWithIndifferentAccess.new(:vehicle=&amp;gt;HashWithIndifferentAccess.new(:vehicle_type=&amp;gt;'Car', :make=&amp;gt;'Porche', :model=&amp;gt;'Cayenne'))
=&amp;gt; {&amp;quot;vehicle&amp;quot;=&amp;gt;{&amp;quot;vehicle_type&amp;quot;=&amp;gt;&amp;quot;Car&amp;quot;, &amp;quot;make&amp;quot;=&amp;gt;&amp;quot;Porche&amp;quot;, &amp;quot;model&amp;quot;=&amp;gt;&amp;quot;Cayenne&amp;quot;}}
vehicle = Vehicle.new params[:vehicle]
=&amp;gt; #&amp;lt;Vehicle id: nil, name: nil, vehicle_type: nil, created_at: nil, updated_at: nil, make: &amp;quot;Porche&amp;quot;, model: &amp;quot;Cayenne&amp;quot;&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Already we can see there is a problem.  The user sent back a request to build a Car, but what is being assembled is a generic Vehicle.  The reasoning is pretty straightforward: you asked for a new Vehicle, not a new Car, so you got a new Vehicle.  Perhaps too graciously, Rails assumed that you knew what you were asking for.  Unforunately, you don't -- the &lt;em&gt;user&lt;/em&gt; knows what is being created but you are clueless.  You could try to build a big case statement, but that's very messy and you have to update it each time you add or remove a class from the hierarchy.  It also suffers from the fact that it's too concrete; you can't transport your knowledge to any other STI implementation.&lt;/p&gt;

&lt;h2&gt;An STI Factory Method&lt;/h2&gt;
&lt;p&gt;This sounds like a classic case for the Factory Method design pattern.  One of my favorite design pattern books (&lt;a href=&quot;http://www.oreilly.com/catalog/hfdesignpat/&quot;&gt;Head First Design Patterns&lt;/a&gt;) says that this pattern &quot;defines an interface for creating an object, but lets subclasses decide which class to instantiate.&quot;  If we translate that to Rubyisms and consider our problem, it sounds like we need a module (interface) that will mix into a class that will help the class pick from among its subclasses when it's asked for something new.&lt;/p&gt;

&lt;p&gt;I've taken a stab at this a few times and never liked the results.  Most of the time it felt like I was injecting too much code.  I also got somewhat inconsistent results from the class-level array I was trying to build to maintain the list of subclasses.  Recently I was working on a different problem and stumbled on some information that I'd forgotten from my first dance with Rails.  I know that &lt;a href=&quot;http://www.manning.com/black/&quot;&gt;David Black&lt;/a&gt; told me that ActiveRecord maintained a protected list of subclasses just for STI, but it was washed away in the grey matter (probably because i read it at the beach... I'm a geek.) &lt;/p&gt;

&lt;p&gt;Having been reintroduced to ARec#subclasses again, I've worked out an abstract STI factory.  I built it as a plugin and the essence of it is in the code that gets mixed into the ActiveRecord base_class in the inheritance hierarchy.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def new(*args)
        target_class_name = requested_class_name(args)
        return self.base_class.factory(target_class_name, *args) unless self.name === target_class_name
        super
      end
      
      def factory(requested_class_name, *args)
        requested_class_name = base_class unless has_subclass_named?(requested_class_name)
        requested_class = requested_class_name.constantize
        requested_class.new(*args)
      end
      
      def type_options_for_select
        subclasses.collect{|subclass| [subclass.name.humanize, subclass.name]}
      end
      
      protected
      # Returns true if the STI tree includes a subclass with the specified name
      def has_subclass_named?(subclass_name)
        subclasses.detect{|subclass| subclass.name==subclass_name}
      end

      def requested_class_name(args)
        class_name = self.name
        if args.last.is_a?(Hash)
          requested_class = args.last.delete(self.inheritance_column.to_sym)
          class_name = requested_class unless requested_class.blank? or !has_subclass_named?(requested_class)
        end
        return class_name
      end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We'll read the code from the bottom up, mostly so that the helper methods make sense when we see them in context.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;div&gt;&lt;em&gt;requested_class_name&lt;/em&gt;&lt;br /&gt;This helper method attempts to determine the name of the subclass that is being requested.  Like Rails, it begins with the assumption that you knew what you were asking for (class_name=self.name) and then it searches the parameters it was passed to see if the :inheritance_column was passed.  If so, it tries to return the value that was requested.  There are two conditions on this: if the class name was blank it assumes that you wanted the class from which you requested something new.  If you supplied a value but that value is not a subclass it assumes it was a typo (kinder than assuming you were a fool :-)  For both cases it falls back to the class_name of the orignal class; otherwise it overrides with a subclass name.  An important thing to note is that the subclass name is deleted from the options passed to the method.  This is done to prevent an infinite loop but it means that you've got to keep a copy of the returned value.&lt;/div&gt;&lt;/li&gt;
&lt;li&gt;&lt;div&gt;&lt;em&gt;has_subclass_named?&lt;/em&gt;&lt;br /&gt;This helper method checks the list of subclasses for the (base) class and makes sure that the requested class actually exists as a subclass.&lt;/div&gt;&lt;/li&gt;
&lt;li&gt;&lt;div&gt;&lt;em&gt;type_options_for_select&lt;/em&gt;&lt;br /&gt;This is a convenience method for the select/select_tag.  It builds an array that can be used as the options source with a human readable name for the class as the text and the class name as the value.&lt;/div&gt;&lt;/li&gt;
&lt;li&gt;&lt;div&gt;&lt;em&gt;factory&lt;/em&gt;&lt;br /&gt;This method requires the name of the subclass.  It takes advantage of the fact that Ruby classes are global constants (hence the call to constantize) to get a handle on the requested class and then invokes 'new' on it, passing in the parameters it received.&lt;/div&gt;&lt;/li&gt;
&lt;li&gt;&lt;div&gt;&lt;em&gt;new&lt;/em&gt;&lt;br /&gt;This is the part that I like most about the plugin.  The first thing that it does is check to see if the class you requested differs from the class that is trying to fill the request.  If so, it automatically to the factory method and if not you proceed with the default 'new' behavior.  The advantage to this is that you never  &lt;em&gt;have&lt;/em&gt; to know what you're trying to create and you don't &lt;em&gt;have&lt;/em&gt; to remember to use the facotry method.  You can just use new (or create) on this class like every other class... and it will figure out what you meant to do.&lt;/div&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With that in place things look a bit different for the VehiclesController.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;class Vehicle &amp;lt; ActiveRecord::Base
  has_sti_factory
  
  def self.inheritance_column
    'vehicle_type'
  end
end
...

params = HashWithIndifferentAccess.new(:vehicle=&amp;gt;HashWithIndifferentAccess.new(:vehicle_type=&amp;gt;'Car', :make=&amp;gt;'Porche', :model=&amp;gt;'Cayenne'))
=&amp;gt; {&amp;quot;vehicle&amp;quot;=&amp;gt;{&amp;quot;vehicle_type&amp;quot;=&amp;gt;&amp;quot;Car&amp;quot;, &amp;quot;make&amp;quot;=&amp;gt;&amp;quot;Porche&amp;quot;, &amp;quot;model&amp;quot;=&amp;gt;&amp;quot;Cayenne&amp;quot;}}

vehicle = Vehicle.new params[:vehicle]
=&amp;gt; #&amp;lt;Car id: nil, name: nil, vehicle_type: &amp;quot;Car&amp;quot;, created_at: nil, updated_at: nil, make: &amp;quot;Porche&amp;quot;, model: &amp;quot;Cayenne&amp;quot;&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now all I have to do is figure out how to make the VehiclesController fulfill that &quot;create Porche Cayenne&quot; request. :-)&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>ryan</name>
    </author>
    <id>tag:upstaterb.org,2008-03-07:17</id>
    <published>2008-03-07T04:19:00Z</published>
    <updated>2008-03-18T13:22:10Z</updated>
    <category term="Meetings"/>
    <category term="meeting"/>
    <link href="http://upstaterb.org/2008/3/7/meeting-directions" rel="alternate" type="text/html"/>
    <title>Meeting Directions</title>
<content type="html">
            &lt;p&gt;Currently meetings are held the 4th Tuesday at lunchtime (12pm) at &lt;a href=&quot;http://www.immedion.com&quot;&gt;Immedion&lt;/a&gt;.&lt;/p&gt;


	&lt;h2&gt;Immedion Office (see the A?)&lt;/h2&gt;


	&lt;p&gt;&lt;strong&gt;Update&lt;/strong&gt;: The door that you will enter is actually toward the middle of the left side of the building (in this picture). Simply park in the parking lot closest to I-85 and walk toward the middle fo the building.&lt;/p&gt;


	&lt;p&gt;&lt;a href=&quot;http://maps.google.com/maps?f=q&amp;amp;#38;hl=en&amp;amp;#38;geocode=&amp;amp;#38;q=Immedion,+greenville,+sc&amp;amp;#38;ie=UTF8&amp;amp;#38;ll=34.810526,-82.341285&amp;amp;#38;spn=0.02389,0.02193&amp;amp;#38;t=h&amp;amp;#38;z=15&amp;amp;#38;iwloc=A&quot;&gt;&lt;img title=&quot;Immedion&quot; src=&quot;http://upstaterb.org/assets/2008/3/7/immedion2.png&quot; alt=&quot;Immedion&quot; /&gt;&lt;/a&gt;&lt;/p&gt;


	&lt;h2&gt;Directions&lt;/h2&gt;


	&lt;p&gt;From I-85 exit south on Laurens Rd (276). Take your first right at the Carmax dealer on to St. Josephs Dr. You will come to a stop sign. Continue across Ridge Rd. Take your next left through the gate into the parking lot. Immedion&#8217;s front entrance will be in the middle of the building facing you.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>ryan</name>
    </author>
    <id>tag:upstaterb.org,2008-02-26:16</id>
    <published>2008-02-26T16:10:00Z</published>
    <updated>2008-02-26T16:15:40Z</updated>
    <category term="Meetings"/>
    <category term="meeting"/>
    <link href="http://upstaterb.org/2008/2/26/updated-directions-to-today-s-meeting" rel="alternate" type="text/html"/>
    <title>Updated Directions to Today's Meeting</title>
<content type="html">
            &lt;p&gt;From Rick&#8230;&lt;/p&gt;

&lt;blockquote&gt;
    &lt;p&gt;The second link is closer but their building is located at the end of the first large parking lot. So, if you are coming from 85 and you have turned off on to Laurens Road you will make a right turn at the first light past CarMax and follow that around past the traffic light and turn right at the next side street. There is a big sign saying something like Gold Park. Follow this side street around to the large parking lot. As you go around you will see a small temporary sign where you will turn into the parking lot closest to Immedion. If anyone has a problem finding Immedion give me a call at 313-8361 and I&#8217;ll try to  guide you in.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href=&quot;http://maps.google.com/maps?f=q&amp;amp;amp;hl=en&amp;amp;amp;geocode=6783720929672207307,34.806685,-82.342400&amp;amp;amp;q=78+Global+Drive,+Suite+100,+Greenville,+SC+29607+(Immedion,+LLC)&amp;amp;amp;ie=UTF8&amp;amp;amp;ll=34.8068,-82.341628&amp;amp;amp;spn=0.007479,0.013475&amp;amp;amp;t=h&amp;amp;amp;z=17&amp;amp;amp;iwloc=addr&quot;&gt;Here&#8217;s &#8220;the second link&#8221; he&#8217;s referring to.&lt;/a&gt; See you at noon!&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>andy</name>
    </author>
    <id>tag:upstaterb.org,2008-02-20:15</id>
    <published>2008-02-20T14:00:00Z</published>
    <updated>2008-07-29T13:56:31Z</updated>
    <category term="Ruby"/>
    <category term="andy"/>
    <category term="duck-typing"/>
    <category term="interface"/>
    <category term="ruby"/>
    <link href="http://upstaterb.org/2008/2/20/if-it-quacks-like-a-duck" rel="alternate" type="text/html"/>
    <title>If it quacks like a duck...</title>
<content type="html">
            &lt;h2&gt;If it quacks like a duck...&lt;/h2&gt;
&lt;p&gt;duck-typing is the Way of Ruby and Rails programming.  The phrase &lt;a href=&quot;http://en.wikipedia.org/wiki/Duck_typing&quot;&gt;attributed to James Whitcomb Riley&lt;/a&gt; refers to the preference in Ruby and Rails to be concerned with &lt;em&gt;what an object does&lt;/em&gt; (methods and attributes) rather than what an object is (it's class).  That makes a lot of sense from a modeling perspective.  We create classes as representations of like things, but we really deal with them in terms of the way we get to the distinguishing attributes and the kinds of things that it can do because it is a member of that group.&lt;/p&gt;
&lt;p&gt;It makes even more sense from a Rails perspective.  One of the great mantras of Rails programming is the DRY principle: Don't Repeat Yourself.  A primary means of not repeating yourself is to capture reusable &lt;em&gt;functionality&lt;/em&gt; in modules and mix those modules into the classes that need to be able to do those kinds of things.  Modules are, first and foremost, abstractly written collections of methods... ways of describing how a duck quacks...&lt;/p&gt;
&lt;p&gt;Duck typing is more than just an interface implementation.  In most static languages the emphasis is on grabbing a particular interface on an object and then making use of that interface as a contract for interaction.  With duck typing you really could not care less whether or not you have an interface.  You really only care about whether or not the duck can quack.  So you ask it:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;duck.respond_to?(:quack)&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;How I learned to love ducks&lt;/h2&gt;
&lt;p&gt;Okay, so all the duck typing talk may be old hat to you by now.  No matter.  It was old hat to me, too.  I just forgot to do it.  Call it old habits dying hard but my code was littered with type-checking. &lt;/p&gt;
&lt;p&gt;A particularly bad area of my largest application is designed to allow the end user to set up their own business processes.  The code is full of subclasses that each perform one business function and the user hooks them up to design their larger processes.  Where it begins to suffer is from the &quot;all roads lead to Rome&quot; problem.  For our customers there is a central object with which they deal, but different users will typically get a handle on it through a different association.  Rather than force the user to navigate up the object graph we decided to let the process step do the navigation for them.  Falling back on old habits I'd have code looking like this&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def apply(target_object, attributes={})
  case
    when target_object.is_a?(Widget)
      return target_object.foo.bar! attributes
    when target_object.is_a?(Cog)
      return target_object.foo.bar! attributes
    when target_object.is_a?(Foo)
      return target_object.bar! attributes
  end
  raise(ArgumentError, &amp;quot;No, foo on you!&amp;quot;) 
end&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The basic idea is to call the bar! method on a Foo class object, but allow the user to apply the process in any context that knows how to navigate up to the Foo class object (including a Foo instance itself).  Obviously the repetition was screaming for some refactoring.  Enter duck typing.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def apply(target_object,  attributes)
  foo = target_object.respond_to?(:foo) ? target_object.foo : target_object
  raise(ArgumentError, &amp;quot;Duck foo on you&amp;quot;) unless foo.respond_to?(&amp;quot;bar!&amp;quot;)
  foo.bar! attributes
end&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Duck typing brings a lot of advantages to that code.  Obviously it eliminates the repetition.  An important corollary is that it reduces the code base so there is less to maintain and less to break.  Duck typing in this scenario also decouples the method from the classes that might need to use it.  This is important in two regards.  First, it means that I can eliminate one of those classes like the Widget class and not have to modify all the places that refer to the Widget class to eliminate 'undefined constant' errors.  Second, it means that I can now introduce &lt;em&gt;new&lt;/em&gt; objects that have a handle on the Foo class and automatically gain the ability to use this process step &lt;em&gt;without modification&lt;/em&gt;.  A less obvious point is that the code now fails more quickly if it's passed a target object that doesn't know Foo; it does not have to wait until all the branches of the case statement fail.&lt;/p&gt;
&lt;p&gt;In my opinion, the nicest part of the duck-typing focused refactoring is that it makes the intentions of the method much clearer.  Like a really good joke or a really bad pun, the punch is in the final line.  What's the objective?  To call 'bar!' with the appropriate attributes on a Foo instance.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://upstaterb.org/">
    <author>
      <name>andy</name>
    </author>
    <id>tag:upstaterb.org,2008-02-14:12</id>
    <published>2008-02-14T18:00:00Z</published>
    <updated>2008-07-29T13:56:49Z</updated>
    <category term="Ruby"/>
    <category term="andy"/>
    <category term="proc"/>
    <category term="ruby"/>
    <link href="http://upstaterb.org/2008/2/14/objective-fun-even-methods-can-be-objects" rel="alternate" type="text/html"/>
    <title>Objective fun: Even methods can be objects</title>
<content type="html">
            &lt;h2&gt;Even Methods Can Be Objects&lt;/h2&gt;
&lt;p&gt;One of the great things about Ruby is the extent to which everything is an object.  There are significantly fewer 'primitives' in Ruby than in any other language with which I've worked.  Even numbers are objects.  Even &lt;em&gt;methods&lt;/em&gt; are objects.  Well, at least they can be.&lt;/p&gt;

&lt;h2&gt;Say Hello to My Little Friend Proc&lt;/h2&gt;
&lt;p&gt;Methods, at least code blocks, can become objects through the Proc class.  As the second edition of &lt;em&gt;Programming Ruby&lt;/em&gt; says it:
&lt;blockquote&gt;Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables. &lt;/blockquote&gt;  Huh?  Basically, the Proc class lets you wrap up a block of code in an object, call it some place, and when it's called it's aware of the context from which it was called.  GoF fans will probably recognize this as a form of the command pattern.&lt;/p&gt;
&lt;p&gt;Okay, let's get down to brass tacks.  As you'd expect, you create a new Proc instance by calling new.  This method accepts a block with an arbitrary number of block parameters.  Why an arbitrary number of them?  Because those block parameters are going to become the parameters you use when you invoke the method you're wrapping up.  Again, let's defer to &lt;em&gt;Programming Ruby&lt;/em&gt; and look at their example:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def genTimes(factor)
  return Proc.new {|n| n*factor }
end

times3 = genTimes(3) 

times3.call(12)  » 36&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So what's going on here...  the genTimes method accepts an argument called 'factor' and creates a Proc instance (a wrapped up method) with it.  The wrapped up method accepts a single parameter it calls 'n' and returns the result of multiplying n and factor.  Since this is a closure, the Proc is aware of the surrounding context and it pulls in 'factor' from genTimes.  In the call 'genTimes(3)', factor is assigned the value 3 (duh), so the result of the call is to hand back an object-wrapped method that calculates n * 3.&lt;/p&gt;
&lt;p&gt;As the Proc basically implements the command pattern you can use this object by invoking the command -- sending the 'call' message.  In the example above the method expects one parameter (n) which is why the next-to-last line says, 'times3.call(12)'... the time3 object has a method that multiplies an argument by 3, and when called with the argument 12 you get 12 * 3 = 36.  That's not quite so painful.&lt;/p&gt;
&lt;h2&gt;So Where's the Fun?&lt;/h2&gt;
&lt;p&gt;The 'fun' obviously lies in the way you can use the procs.  In his brilliant book &lt;em&gt;&lt;a href=&quot;http://safari.awprofessional.com/9780321445612&quot;&gt;The Rails Way&lt;/a&gt;&lt;/em&gt; early adopter Obie Fernandez provides a great example that really struck a chord with me (I won't spoil the ending... buy the book!).  At the end of his chapter on helpers Fernandez refactors a very specific partial into a very general custom helper.  What struck a chord was that the partial essentially needed a 'description' method for the objects that it rendered.  Obviously that was not a problem in the very specific original implementation, but it became one when trying to generalize the code.  Enter Proc, stage right.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def cool_helper(collection, opts={})
...
opts[:description] ||= Proc.new{|item| itemd.description}
...
render :partial =&amp;gt; 'shared/cool_partial',
  :locals =&amp;gt; {:description =&amp;gt; opts[:description], ... }
end&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In line 3 the refactored helper method creates a default Proc instance to handle the initial need for the description.  All the proc does is call the 'description' method on the object that it's passed.  The nice thing about this is that the default functionality matches what was being done in the original implementation.  More importantly, though, this proc is being created as one of the optional parameters that can be supplied by the caller.  That means if you would like to reuse the helper with an object that does not have a 'description' method (accessor or otherwise) then you can supply your own 'description' method &lt;em&gt;to the renderer not in your object&lt;/em&gt;.  For example, what if you now wanted to use this helper to display a list of sports teams and you wanted the description to be the 'name' attribute?&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;cool_helper my_teams, :description=&amp;gt;Proc.new{|item| item.name}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And &lt;em&gt;there&lt;/em&gt; is where it gets fun.  Since the proc is an object you can pass it between other objects, but what you're &lt;em&gt;really&lt;/em&gt; passing is the ability to perform some custom functionality.  The beauty, of course, is that the partial gets to remain blissfully ignorant of the implementation.  It does not know or care whether it's invoking the description or name or any other attribute or method.  It simply issues the 'call' method and the wrapped up function handles the rest.  Something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;html&quot;&gt;&amp;lt;div class=&amp;quot;description&amp;quot;&amp;gt;&amp;lt;br/&amp;gt;
  &amp;lt;%= description.call(item) %&amp;gt;&amp;lt;br/&amp;gt;
&amp;lt;/div&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the snippet above, just remember that 'description' is the name of the local variable passed into the partial through the :locals hash... and that variable is the object-wrapped method (Proc) that calls the description on your item.&lt;/p&gt;
          </content>  </entry>
</feed>
