<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description></description><title>thoughts.inject(world)</title><generator>Tumblr (3.0; @andyvanasse)</generator><link>http://blog.andyvanasse.com/</link><item><title>A Different Form of Ancestry</title><description>&lt;p&gt;Okay, this is not really a code-related post.  Several months ago I sat down with my son and tried to teach him some good coding concepts.  It didn&amp;#8217;t last too long because&amp;#8230; I had no plan.  I didn&amp;#8217;t really think much of it until last night.&lt;/p&gt;
&lt;p&gt;We were on our way to a soccer practice and talking about things that had gone on during the day.  My son is taking an engineering class that focuses on mechanical engineering and told me that their next project is to build a bridge.  The test for the bridge will be to support a bucket into which the teacher will pour water until the bridge collapses.  Apparently the student whose bridge supports the greatest weight gets an &amp;#8216;A&amp;#8217;.&lt;/p&gt;
&lt;p&gt;The objective is simple enough. What floored me was the way he tried to explain it to me even after laying out all the guidelines.  He said, &amp;#8220;So I have to build it knowing that I am going to break it.  It&amp;#8217;s like when you write software and write a test first, knowing that it&amp;#8217;s going to fail, so that you can write the least amount of software possible to make it work.&amp;#8221;&lt;/p&gt;
&lt;p&gt;Wow.  I guess the lesson got through much more than I thought!&lt;/p&gt;
&lt;p&gt;Now, go build your own Ancestry: pass along your best coding skills to someone else.&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/17209590793</link><guid>http://blog.andyvanasse.com/post/17209590793</guid><pubDate>Tue, 07 Feb 2012 09:30:00 -0500</pubDate></item><item><title>getting into ancestry</title><description>&lt;p&gt;Heading into &lt;em&gt;The Big Rewrite&lt;/em&gt; I finally took the opportunity to play with the &lt;a title="ancestry gem" target="_blank" href="https://github.com/stefankroes/ancestry"&gt;ancestry gem&lt;/a&gt;.  Initially developed as a replacement for for acts_as_tree, ancestry has evolved to something much more akin to nested-set support in a tree-like structure.  The advances allow you to pluck out a entire subtree or hierarchy path in a single trip to the database.  Awesome.&lt;/p&gt;
&lt;p&gt;The one thing that I wish we had for ancestry is a clear upgrade path for those of us who discovered ancestry after building up an application with acts_as_tree.  Stefan has kindly renamed the initializing &amp;#8216;acts_as_tree&amp;#8217; method to &amp;#8216;has_ancestry&amp;#8217; which is a step in the right direction.  Hopefully it will bother me enough to actually do something about it&amp;#8230;&lt;/p&gt;
&lt;p&gt;The ancestry gem has greatly simplified a tangential issue in the code base.  My first use of ancestry was in my Account model.  In this particular application Account is hierarchical in order to allow higher-level accounts to establish rules that must be followed by lower-level accounts.  Specifically, the corporation (root) will set rules for everyone, the regional manager (child of corporate) may extend those rules, and the local account (leaf of the tree) is subject to both of them.&lt;/p&gt;
&lt;p&gt;With acts_as_tree the solution to this was not difficult but it was time consuming. First, we created a method to walk up the hierarchy and collect the parent nodes of the tree until we hit the root node.  Each parent node is unshifted into the array so that the resulting array index corresponds to the depth of the node in the hierarchy (index 0 is the root node, etc).  Another method can then iterate over that hierarchy and collect the rules into a single array as shown below.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class Account &amp;lt; ActiveRecord::Base
  has_ancestry

  ...

  def account_hierarchy
    hierarchy = [self]
    current_account = parent

    while(!current_account.nil?) do
      hierarchy.unshift current_account
      current_account = current_account.parent
    end
    return hierarchy
  end
 
  def collect_from_hierarchy(collection_name)
    account_hierarchy.collect{|acct| acct.send(collection_name) }.flatten.compact
  end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;While straight-forward, this code clearly will not scale all that well.  We will have 2N database cycles (N=node depth) every time we need to retrieve a collection of objects.  Yuck.&lt;/p&gt;
&lt;p&gt;The ancestry gem dramatically reduces this.  The gem provides a method called &amp;#8216;path&amp;#8217; (and corresponding &amp;#8216;path_ids&amp;#8217;) that returns a set roughly equivalent to the &amp;#8216;account_hierarchy&amp;#8217; method shown above.  The win is not that we no longer need the &amp;#8216;account_heirarchy&amp;#8217; method (obviously the equivalent method exists somewhere) but that ancestry manages to build the path collection &lt;em&gt;in one trip to the database&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;That bit of inspiration led to a refactoring of the &amp;#8216;collect_from_hierarchy&amp;#8217; method.  Since we have the ids of the accounts it was obvious that we could retrieve the collection of rules in just one trip as well.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class Account &amp;lt; ActiveRecord::Base
  has_ancestry

  ...

  def collect_from_hierarchy(collection_name)
    Object.const_get(collection_name.to_s.classify).where :account_id =&amp;gt; path_ids
  end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this refactoring we are taking advantage of the fact that Ruby classes are constants.  We accept the name of the collection we would like to assemble from the hierarchy, convert to a string (allowing the user to call it with a symbol), and then get the class name equivalent by calling classify and finally grab a handle to the class by asking Ruby to retrieve the class from the known constants.  We then ask the class to return the collection of rules where the account_id for the rule is one of the members of the path_ids.  As an added bonus, the refactoring also takes advantage of scopes so that the caller may chain additional scopes as necessary.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  acct.collect_from_hierarchy(:birthdays).order(:born_on)
  acct.collect_from_hierarchy(:salaries).order(:amount).paginate :page =&amp;gt; params[:page]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Admittedly, this refactoring was available earlier.  The &amp;#8216;account_hierarchy&amp;#8217; method could have been written to return an array of ids rather than the objects themselves.  ancestry provided the inspiration by making that fact obvious.  We stand on the shoulders of giants, indeed.&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/5836930431</link><guid>http://blog.andyvanasse.com/post/5836930431</guid><pubDate>Wed, 25 May 2011 13:29:40 -0400</pubDate></item><item><title>...and?</title><description>&lt;blockquote&gt;&amp;#8216;and&amp;#8217; and &amp;#8216;or&amp;#8217; originate (like so much of Ruby) in Perl. In Perl, they were largely used to modify control flow, similar to the &amp;#8216;if&amp;#8217; and &amp;#8216;unless&amp;#8217; statement modifiers. A common Perl idiom is:&lt;br/&gt;&lt;br/&gt; do_something() or die &amp;#8220;It didn&amp;#8217;t work!&amp;#8221;;&lt;br/&gt;&lt;br/&gt;The &amp;#8216;and&amp;#8217; and &amp;#8216;or&amp;#8217; keywords serve the same purpose in Ruby. Properly understood, &amp;#8216;and&amp;#8217; and &amp;#8216;or&amp;#8217; are &lt;strong&gt;control flow operators&lt;/strong&gt;, not boolean operators.&lt;/blockquote&gt;
&lt;p&gt;I just ran across the quote above in &lt;a href="http://avdi.org/devblog/2010/08/02/using-and-and-or-in-ruby/"&gt;Avdi&amp;#8217;s explanation of &amp;#8216;and&amp;#8217; vs &amp;#8216;&amp;amp;&amp;amp;&amp;#8217;&lt;/a&gt;.  I almost skipped the article but am glad that I read it.  This may be the first time that I have seen an explanation of &lt;em&gt;why&lt;/em&gt; the operators differ rather than &lt;em&gt;how&lt;/em&gt; they differ.  The former makes it much easier to remember the difference.  Thanks, Avdi!&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/893743948</link><guid>http://blog.andyvanasse.com/post/893743948</guid><pubDate>Mon, 02 Aug 2010 12:43:11 -0400</pubDate></item><item><title>Constant-ly?</title><description>&lt;p&gt;I&amp;#8217;ve gone back and forth about what should constitute a good use of class-level constants and a recent project has brought this question up once again.  In this project there are basically two different uses for class-level constants.  The first, and less frequent, use of class-level constants serves to identify &amp;#8220;magic values&amp;#8221;.  The second use is to define a closed set of options.&lt;/p&gt;
&lt;h2&gt;Class Constants as Magic Values&lt;/h2&gt;
&lt;p&gt;&amp;#8220;Magic values&amp;#8221;, if you are not familiar with the term, are those values that require you to change the response of a class or class instance to a message.  Usually you find them in flow control logic such as if-then or case statements.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class AtBat
  MAX_BALLS = 4
  MAX_STRIKES = 3

  attr_reader :pitches, :result, :strikes, :balls

  def initialize(first_pitch = nil)
    @balls = @strikes = 0
    @pitches = [ ]
    @result = nil
    add_pitch( first_pitch ) unless first_pitch.nil?
  end

  def add_pitch(pitch_result)
    @pitches ||= [ ]
    @pitches.push pitch_result

    case pitch_result
      when :foul
        add_strike if @strikes &amp;lt; MAX_STRIKES-1
      when :ball
        add_ball
      when :strike
        add_strike
      else
        @result = pitch_result
    end
  end

  def active?
    !@result.nil?
  end

  private
    def add_strike
      if active?
        @strikes += 1 
        @result = :strike_out if struck_out?
      end
    end

    def struck_out?
      @strikes == MAX_STRIKES
    end

    def add_ball
      if active?
        @balls += 1 
        @result = :walked if walked?
      end
    end

    def walked?
      @balls == MAX_BALLS
    end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the code above the class-constants MAX_BALLS and MAX_STRIKES are magic values.  They represent different &amp;#8220;high water marks&amp;#8221; for the AtBat class.  Each instance should respond differently when a pitch is a ball and there are less than MAX_BALLS of them in the AtBat.&lt;/p&gt;
&lt;p&gt;This is the best, and possibly only, justifiable use of class constants.  Using constants in this case accomplishes two important objectives.  First, it pulls the magic values into one place so that they can easily be maintained.  If the rules of baseball changed to permit more balls or strikes in at bat you simple change the class-constant and you&amp;#8217;re done.  Second, the class constant is more expressive of the intent than the value.  Why use &amp;#8220;3&amp;#8221; when evaluating the number of strikes?  Because that&amp;#8217;s the maximum allowed.&lt;/p&gt;
&lt;h2&gt;Class Constants as Closed Options&lt;/h2&gt;
&lt;p&gt;A special case of magic values is when the constant represents a closed set of options for the class.  For example, consider when my favorite baseball team, the Boston Red Sox, conducts a contest during the season to give away a pair of tickets to a game and then does something I detest: they restrict entry to residents of the New England states.  (Yes, I&amp;#8217;m crazy enough to drive the thousand miles between my house and Fenway to see a game.)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class Entrant
  ELIGIBLE_STATES = %w{CT MA ME NH RI VT}
  attr_accessor :first_name, :last_name, :dob, :email, :street, :city, :state_abbrev

  def valid?
    new_england_resident? and over_18?
  end

  private
    def new_england_resident?
      ELIGIBLE_STATES.include? @state_abbrev
    end

    def over_18?
      @dob &amp;lt; 18.years.ago
    end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In the code above the ELIGIBLE_STATES constant is used as a special type of magic value.  The instance reacts differently based on whether or not one of the attributes &amp;#8220;matches&amp;#8221; the constant.  To that extent the closed option type of class constant makes some sense.  It does often have an irritating side effect (constant redeclaration warnings when restarting a Rails application) but that&amp;#8217;s the main downside.&lt;/p&gt;
&lt;h2&gt;More than Magic?&lt;/h2&gt;
&lt;p&gt;The problem that I have seen fairly often is that these class constants that begin as a closed set of options tend to evolve over time.  The list of states shown above, for example, may take on an additional property for reporting purposes such as a state-specific tax rate for reporting the tickets as &amp;#8220;income.&amp;#8221;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class Entrant
  ELIGIBLE_STATES = {:CT=&amp;gt;0.07, :MA=&amp;gt;0.09, :ME=&amp;gt;0.07, :NH=&amp;gt;0.0, :RI=&amp;gt;0.07 :VT=&amp;gt;0.09}
  attr_accessor :first_name, :last_name, :dob, :email, :street, :city, :state_abbrev

  def valid?
    new_england_resident? and over_18?
  end

  def extended_ticket_value( ticket_price, qty )
    qty * ticket_price * (1 + ELIGIBLE_STATES[@state_abbrev.to_sym])
  end

  private
    def new_england_resident?
      ELIGIBLE_STATES.include? @state_abbrev
    end

    def over_18?
      @dob &amp;lt; 18.years.ago
    end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Before you know it there are new &amp;#8220;constants&amp;#8221; springing up to deal with other flow control changes related to the first constant.  Tax rates, shipping charges, and who knows what else might change based on the state of residence for the Entrant.  This is where the problem lies.  Because the needs emerged slowly they feel like a simple, organic extension of the class.  But they&amp;#8217;re not.&lt;/p&gt;
&lt;p&gt;They are classes in and of themselves.&lt;/p&gt;
&lt;p&gt;These classes are not constants in the traditional, magic value sense.  They are classes with constant data.  That is, they are classes whose data is set and known at the time the software is developed.  Just like other classes, they deserve their own class body.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class State
  NEW_ENGLAND_STATES = %w{CT MA ME NH RI VT}
  attr_reader :state_abbrev, :tax_rate, :shipping_charge

  def initialize(state_abbrev, tax_rate, shipping_charge)
    @state_abbrev, @tax_rate, @shipping_charge = state_abbrev, tax_rate, shipping_charge
  end

  def new_england?
    NEW_ENGLAND_STATES.include? @state_abbrev
  end

  def find_by_abbrev( abbrev )
    @@states.detect{|state| state.state_abbrev == abbrev}
  end

  @@states = {
    new(:CT, 0.07, 1.50),
    new(:MA, 0.09, 0.50),
    new(:ME, 0.07, 1.75),
    new(:NH, 0.00, 1.75),
    new(:RI, 0.07, 0.75),
    new(:VT, 0.09, 2.50),
    new(:SC, 0.07, 4.00)
  }
end

class Entrant
  attr_accessor :first_name, :last_name, :dob, :email, :street, :city, :state_abbrev

  def valid?
    new_england_resident? and over_18?
  end

  def extended_ticket_value( ticket_price, qty )
    qty * ticket_price * (1 + state_of_residence.tax_rate)
  end

  private
    def new_england_resident?
      state_of_residence.new_england?
    end

    def state_of_residence
      State.find_by_abbrev( @state_abbrev )
    end

    def over_18?
      @dob &amp;lt; 18.years.ago
    end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;By pulling this class of constant data out as a unique class we gain similar advantages to the use of constants as magic values.  The class now encapsulates all the knowledge about how to deal with a particular state and properly separates those concerns from how to deal with an Entrant.  The Entrant code is even more expressive of its intent (e.g., state_of_residence.tax_rate vis-a-vis ELIGIBLE_STATES[@state_abbrev.to_sym]).&lt;/p&gt;
&lt;p&gt;Admittedly, something very similar to this could be accomplished with a database-backed class like an ActiveRecord or MongoMapper derived class.  The constant nature of the data, however, always makes that feel a little improper even if the end user has no access to the maintenance function.  In the back of my mind I always worry that a necessary record will be inadvertently dropped so I want to &amp;#8216;freeze&amp;#8217; it in code.&lt;/p&gt;
&lt;p&gt;What about you?  How do you deal with these kinds of classes of constant data?  Do you recognize them up front?  Shuttle them off to the database?&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/595559646</link><guid>http://blog.andyvanasse.com/post/595559646</guid><pubDate>Thu, 13 May 2010 12:22:59 -0400</pubDate><category>ruby</category></item><item><title>RSpec best practices</title><description>&lt;p&gt;A few days ago Philippe Creux posted his &lt;a title="RSpec Best Practices and Tips" target="_blank" href="http://eggsonbread.com/2010/03/28/my-rspec-best-practices-and-tips/"&gt;RSpec Best Practices and Tips&lt;/a&gt;.  The post is well worth reading even if you prefer another test framework (you &lt;em&gt;are&lt;/em&gt; testing, right?!) because there are several tips that are applicable to TDD more broadly than rspec alone.  Of all the tips there are two that I cannot re-emphasize strongly enough: &amp;#8220;Only One Expectation Per It Block&amp;#8221; and &amp;#8220;(Over)Use Describe and Context&amp;#8221;.&lt;/p&gt;
&lt;h2&gt;Single Expectation Tests&lt;/h2&gt;
&lt;p&gt;The &amp;#8220;one expectation&amp;#8221; tip is more broadly expressed as &amp;#8220;each test should make only one assertion.&amp;#8221;  Philippe&amp;#8217;s example is a good one: rather than have one test that asserts that all expected attributes are present, have multiple tests that assert that individual attributes are present.  The advantage of this approach lies in its granularity.  The &amp;#8220;one expectation&amp;#8221; way allows to you to more quickly identify when multiple expectations have been violated.  Why?  Because a monolithic test will fail on the first failed expectation even though there may be multiple points of failure behind it.&lt;/p&gt;
&lt;p&gt;The impetus for a monolithic test is typically the perceived advantage of collecting all the similar expectations into one place.  Grouping the expectations does make it simpler to determine where to alter or extend that type of testing.  Taking Philippe&amp;#8217;s example, if you wanted to replace &amp;#8216;age&amp;#8217; in the list of attributes with &amp;#8216;dob&amp;#8217; (date of birth) and add &amp;#8216;shirt_size&amp;#8217; then you would know right where to go to do that type of thing.  For this reason I would make one additional recommendation that I&amp;#8217;ve mentioned in the past: use the dynamic nature of ruby to your advantage by using code to create expectations.  For example, rather than the recommended syntax&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  it { should respond_to :name }
  it { should respond_to :age }
  it { should respond_to :gender }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Try the following&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
[:name, :age, :gender].each do |expected_attribute|
  it { should respond_to expected_attribute }
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code retains the advantages of both co-locating similar kinds of tests &lt;em&gt;and&lt;/em&gt; employing discrete &amp;#8220;one expectation&amp;#8221; tests.  Personally I believe it is also more expressive of the intention of the test, all the more when you build blocks for required_attribute or nonnegative_attributes.&lt;/p&gt;
&lt;h2&gt;Context is King&lt;/h2&gt;
&lt;p&gt;The &amp;#8220;(Over)Use Context&amp;#8221; tip is spot on.  Early on in my use of rspec I tended to have code littered with one-off tests.  That is, most of the test code was duplicated except for one or two key parameters.  By using contexts, specifically nested contexts, you can reduce the duplication &lt;em&gt;and&lt;/em&gt; bring sharper focus to what is varying.  Use the outer context to group all those unchanging parameters and let the outer context description identify how they are common.  Then, use the nested context to explicitly declare what is varying.  Importantly, the &lt;em&gt;before&lt;/em&gt; block in each context should set up the test scenario as described by the context.&lt;/p&gt;
&lt;p&gt;As an additional example, consider a class with a state machine.  The state machine begins in the &amp;#8216;pending&amp;#8217; state and then moves to the &amp;#8216;active&amp;#8217; state only when the &amp;#8216;activate&amp;#8217; event is triggered.  You might begin testing this scenario as follows.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
describe Thing do
  before :each do
    @valid_attributes = { ... }
  end

  it "should create an instance given valid attributes" do
    lambda{ Thing.create @valid_attributes}.should change(Thing, :count).by(1)
  end

  it "should default to the pending state upon creation" do
    @thing = Thing.create @valid_attributes
    @thing.should be_pending
  end

  context "pending instance" do
    before :each do
      @thing = Thing.create @valid_attributes
    end

    it "should transition to 'active' when activated" do
      lambda{ @thing.activate }.should change(@thing, :state).to('active')
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;From the flow of the code we can see just what was described: if the attributes are valid we can create a new instance and that instance will correctly default to the pending state and from the pending state we can activate the instance and it will become active.  Perfect.  Until.  Until?  Yes, until you have to modify the state machine.  Let&amp;#8217;s say you&amp;#8217;ve run with this code for a while and found a bot probing your application.  To filter out bot created things you decide to  begin with an &amp;#8216;unconfirmed&amp;#8217; state that requires an email confirmation of some type.&lt;/p&gt;
&lt;p&gt;What happens with the tests in this new case?  The second test (default to pending) naturally fails.  So does the third test (transition to active).  Should it?  Probably not.&lt;/p&gt;
&lt;p&gt;What&amp;#8217;s missing is that the before block did not &lt;em&gt;guarantee&lt;/em&gt; that the testing state was what the context claimed that it was.  How do you guarantee such things?  Add an assertion.  This step is commonly overlooked in a lot of tests that I have seen.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  context "pending instance" do
    before :each do
      @thing = Thing.create @valid_attributes
      @thing.should be_pending
    end

    it "should transition to 'active' when activated" do
      lambda{ @thing.activate }.should change(@thing, :state).to('active')
    end
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The only change here is the addition of the assertion to the &lt;em&gt;before&lt;/em&gt; block.  When you re-run the tests, the third test about transitioning to &amp;#8216;active&amp;#8217; will still fail.  However, now the failure will indicate that the error lies with the assertion in the &lt;em&gt;before&lt;/em&gt; block.  Previously we had &lt;em&gt;assumed&lt;/em&gt; the object was in the &amp;#8216;pending&amp;#8217; state because it was the default state.  Now we make that assumption explicit and the test report will quickly help us understand that the failure was in the test setup rather than in the state machine implementation.&lt;/p&gt;
&lt;h2&gt;Personal Preference&lt;/h2&gt;
&lt;p&gt;I don&amp;#8217;t personally care for the shortcuts Philippe recommends.  I don&amp;#8217;t think that the use of &amp;#8216;specify&amp;#8217; is quite as expressive as the typical it-block that invokes it in most rspec code.  This matters to me somewhat because I still hold onto that thin hope that a non-technical person might be able to read an rspec and &amp;#8216;get it.&amp;#8217;  Using the more standard &amp;#8216;it-block&amp;#8217; style also allows me to grep my rspecs for expectations.  The other shortcut &amp;#8212; using braces rather than do/end syntax for declaring tests &amp;#8212; does not seem practical to me.  In practice, only the most trivial tests are written in one line (or maybe I need more deeply nested contexts).&lt;/p&gt;
&lt;h2&gt;More Cowbell!&lt;/h2&gt;
&lt;p&gt;As a final thought, I don&amp;#8217;t think that the&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;lambda{...}.should change(object, :attribute_name)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;syntax is used nearly enough.  I have a preference, for example, to know that calling &amp;#8216;create&amp;#8217; actually creates a new instance rather than fails to throw an exception.  That&amp;#8217;s why in the code snippet above the first test checks to see if invoking create has changed the Thing count by one.&lt;/p&gt;
&lt;p&gt;I have not seen the use of change() used as often with instances but it works just as well.  In the third test above we&amp;#8217;re using it to validate that the state has changed to &amp;#8216;active&amp;#8217;.  You need to be careful with this; change() will fail your code if the final value is correct (ie., ended in &amp;#8216;active&amp;#8217;) but you did not change (ie., started in &amp;#8216;active&amp;#8217; and stayed in &amp;#8216;active&amp;#8217;).&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/503615383</link><guid>http://blog.andyvanasse.com/post/503615383</guid><pubDate>Wed, 07 Apr 2010 13:41:29 -0400</pubDate><category>rails</category><category>rspec</category></item><item><title>Water Drop at 2000 Frames per Second</title><description>&lt;a href="http://www.flixxy.com/water-drop.htm"&gt;Water Drop at 2000 Frames per Second&lt;/a&gt;: &lt;p&gt;Water bounces?&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/437062996</link><guid>http://blog.andyvanasse.com/post/437062996</guid><pubDate>Tue, 09 Mar 2010 11:43:38 -0500</pubDate></item><item><title>Qu’ils mangent de la brioche</title><description>&lt;p&gt;The phrase attributed to Marie Antoinette often mistranslated into English as &amp;#8220;Let them eat cake&amp;#8221; seems particularly appropriate in light of the &lt;a href="http://www.engineyard.com/blog/2010/let-them-code-cake/"&gt;great post by the folks over at Engine Yard&lt;/a&gt;.  The &amp;#8220;cake&amp;#8221; that the French noblewoman referred to was really an enriched bread that the upper classes could dine upon but was generally out of the reach of the starving peasants (all the more during a famine!).  For the Ruby community today, let&amp;#8217;s take it as a challenge to raise our collective game.&lt;/p&gt;
&lt;p&gt;In &lt;u&gt;Clean Code&lt;/u&gt;, &amp;#8220;Uncle Bob&amp;#8221; Martin from Object Mentor made these statements about the Rails community&amp;#8217;s dominant ORM ActiveRecord.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Active Records are special forms of DTOs.  They are data structures with public (or bean-accessed) variables; but they typically have navigational methods like &lt;i&gt;save&lt;/i&gt; and &lt;i&gt;find&lt;/i&gt;.  Typically these Active Records are direct translations from database tables, or other data sources.&lt;/p&gt;
&lt;p&gt;Unfortunately we often find that developers try to treat these data structures as though they were objects by putting business rule methods in them.  This is awkward because it creates a hybrid between a data structure and an object.&lt;/p&gt;
&lt;p&gt;The solution, of course, is to treat the Active Record as a data structure and to create separate objects that contain the business rules and that hide their internal data (which are probably just instances of the Active Record).&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Ouch.  Martin is generally a pretty sharp guy and when he calls out a specific implementation pattern we should take notice.  The statements made me a bit uncomfortable because I am just as addicted to rolling business logic into ARec models as everyone else.&lt;/p&gt;
&lt;p&gt;The EY post could be the game changer.  The technique they describe for model composition was one they created primarily for speeding up tests.  If you haven&amp;#8217;t already taken the time to ready the article, they suggest extracting a certain amount of business logic into a namespaced module and then including that into your ARec-based model.  The advantage is that you can create mock objects for testing, extend them with your module just like their ARec counterpart, and test them without hitting the database.  It&amp;#8217;s a simple but brilliant suggestion.&lt;/p&gt;
&lt;p&gt;But now consider EY&amp;#8217;s approach in light of Martin&amp;#8217;s objection to the abuse of the Active Record pattern in general.  Extracting the business logic into a separate, testable module achieves the goal of decoupling the DTO (Active Record class) from the business logic that acts upon it.  Couldn&amp;#8217;t the EY recommendation become the &lt;i&gt;norm&lt;/i&gt; for building Rails applications?&lt;/p&gt;
&lt;p&gt;One approach along these lines has already been encapsulated into the &lt;a href="http://codaset.com/joelmoss/rails-concerns"&gt;RailsConcerns plugin&lt;/a&gt;.  The idea is fairly simple.  Organize your Rails project similar to most gems: include both a things.rb and things folder in your app/models.  The things.rb will be responsible for including/extending itself using the modules and classes in the things folder.  The plugin provides a simple API for the latter.  Let&amp;#8217;s assume that you have an Employee model and that you break your business logic for the employee down into modules called Employee::Vacation and Employee::Pay, organizing them into appropriately named files in the app/models/employee folder.  In that case you could have an ARec model that deals primarily with data (validations, etc) and brings in other classes/modules for the business logic like so:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class Employee &amp;lt; ActiveRecord::Base
  validates_presence_of :first_name, :last_name, :start_date
  
  concerned_with :pay, :vacation
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;I didn&amp;#8217;t care for the initial justification of RailsConcerns (breaking down a large model) but it now makes a lot of sense based on Martin&amp;#8217;s and EngineYard&amp;#8217;s comments.  The one place that I&amp;#8217;ll still disagree with RailsConcerns is its example of extracting validations to a module; since that seems to be the essence of what DTO &lt;i&gt;is,&lt;/i&gt; it makes sense to stay in the model.&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/385692206</link><guid>http://blog.andyvanasse.com/post/385692206</guid><pubDate>Fri, 12 Feb 2010 11:48:29 -0500</pubDate></item><item><title>New Year's Cleanup: Compact Is Not Necessarily Concise</title><description>&lt;p&gt;To start the New Year off I am having the distinct pleasure of cleaning up bunch of old code.  Aside from my beautiful code (ahem) I am also having the chance to review some other developers and that is leading me to some thoughts about style.&lt;/p&gt;
&lt;h2&gt;Style Lesson 1: Compact is Not Necessarily Concise&lt;/h2&gt;
&lt;p&gt;One of the great things about Ruby is it&amp;#8217;s concise syntax.  Well-written Ruby code is and should be short and to the point.  Unfortunately sometimes the notion of &amp;#8216;short&amp;#8217; gets confused for &amp;#8216;concise&amp;#8217;.  They are not the same thing.  Take, for example, the following &lt;i&gt;deprecated&lt;/i&gt; code that I ran across:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class &amp;lt;&amp;lt; self
    def complete_payment(panel_id)
        Panel.transaction do
          panel = Panel.find(panel_id)
          court_ap_id = Court.find(panel.court_id).accounts_payable.id
          # identify all pending expenses for the panel
          pending_expenses = Financial::RosterExpense.for_panel(panel_id).for_state('approved')
          # collect hash fo summarized rosters to send for journalling to financials
          collection_of_rosters_for_journal_transaction =
            # convert array of hashes to a single hash
            Hash[
              # first group by pay_type
              *pending_expenses.group_by(&amp;amp;:pay_type).collect do |pay_type, roster_by_pay_type|
                # then sub group by payable_to
                roster_by_pay_type.group_by(&amp;amp;:payable_to).collect do |payable_to, roster_by_payable_to|
                    self.financial_transaction_package(pay_type, payable_to, roster_by_payable_to.map(&amp;amp;:amount).sum, roster_by_payable_to.size, User.current_user.id, panel.court_id, court_ap_id)
                end
              end.flatten.collect{|h| h.to_a}.flatten

            ]
          resp = Journal.post_group_of_entries_with_summary_account(collection_of_rosters_for_journal_transaction, panel.court_id, User.current_user.id)
          unless resp.instance_of?(Net::HTTPOK)
            logger.debug("ERRORED in Journaling with #{resp.body}")
            raise ActiveRecord::Rollback
            response = false
          end
        end
        response ||= true
        return response
      end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;W O W.  There&amp;#8217;s a lot going on there, no?  It is arguably &lt;i&gt;short&lt;/i&gt; but not at all concise.  Concise has to do just as much with readability as it does with brevity.  Concise makes things clear and obvious, especially for those of us who get to read what you&amp;#8217;ve left behind.  So let&amp;#8217;s take another stab at that in a way that&amp;#8217;s hopefully more &amp;#8216;concise&amp;#8217;.&lt;/p&gt;
&lt;h2&gt;Known knowns&lt;/h2&gt;
&lt;p&gt;One of the first things that strikes me is the line just below the comment &amp;#8216;identify all pending expenses for the panel.&amp;#8217;  What is not obvious in this code snippet is that this query is repeated several times so it needs drying up.  Further more, note the actual query.  Is it really checking for &amp;#8216;pending&amp;#8217; things?  No, it&amp;#8217;s looking for &amp;#8216;approved&amp;#8217; things.  Duplicated code often does that.  Let&amp;#8217;s extract a function there.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class &amp;lt;&amp;lt; self
  def self.approved_expenses_for( panel_id )
    for_panel( panel_id ).for_state( 'approved' )
  end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Simple enough.  We&amp;#8217;re already working in the Financial::RosterExpense class and the method in question is a class-level method so we can dispense with the class reference.  We can also give the query a descriptive name that matches what it returns.  In this case I&amp;#8217;ve left off the word &amp;#8216;panel&amp;#8217; from the end of the method name simply because I like the way it will read when used: &amp;#8216;approved_expenses_for panel_id&amp;#8217;.  If that does not appeal to you, no big deal.&lt;/p&gt;
&lt;h2&gt;Wielding the Unweildy&lt;/h2&gt;
&lt;p&gt;Take a deep breath and grab a cup of coffee before continuing.  We&amp;#8217;re going to tackle that big chunk in the middle.&lt;/p&gt;
&lt;p&gt;The heart of the Panel.transaction block is simply building up a hash.  The syntax may be a bit unfamiliar and hard to decipher.  One way to instantiate a hash &lt;a href="http://ruby-doc.org/core/classes/Hash.src/M002839.html"&gt;is to call Hash[] passing it an array&lt;/a&gt;.  Hash responds by zipping the array in pairs and returning a hash in which the first, third, fifth, &amp;#8230; entries are the keys and the second, fourth, sixth, &amp;#8230; entries are the values of the hash.  This somewhat infrequent use of Hash is all the more obscured by the fact that the square brackets in the call are separated by a huge code block.  Obviously this needs to be broken down in a way that makes that intention clearer.&lt;/p&gt;
&lt;p&gt;Delving inside the Hash call we see that the expenses are grouped twice (once by pay_type and then by pay_to) and the innermost group is used to call a helper function that returns a hash.  Interestingly, the hash is collected up into an array at each level.  At the end, the nested arrays are flattened, with the inner hash being converted from a hash to an array in the process.  I don&amp;#8217;t know why.&lt;/p&gt;
&lt;h2&gt;Private, get me that expense report&lt;/h2&gt;
&lt;p&gt;The first step in cleaning up this code will be to create another helper function that performs the nested grouping and summary work.  Within the helper function we&amp;#8217;ll add some variables to make some of the calculations more explicit in case we need to modify those calculations in the future.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class &amp;lt;&amp;lt; self
  def approved_expenses_for( panel_id )
    for_panel( panel_id ).for_state( 'approved' )
  end

  def build_expense_summary( expenses )
    expenses.group_by(&amp;amp;:pay_type).collect |pay_type, expenses_by_pay_type|
      expenses_by_pay_type.group_by(&amp;amp;:payable_to).collect do |payable_to, pay_to_expenses|
        payment_amount = pay_to_expenses.map(&amp;amp;:amount).sum
        payment_count = pay_to_expenses.size
        self.financial_transaction_package(pay_type, payable_to, payment_amount, payment_count, User.current_user.id, panel.court_id, court_ap_id)
      end
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It turns out that the &amp;#8216;financial_transaction_package&amp;#8217; helper method is returning a very simple hash.  The key to the hash is a unique id and the value is a hash of transaction attributes associated with that id.  This is useful to know because we can merge these simple hashes together without worrying that we might replace values. In fact, we can perform the merges &lt;i&gt;at multiple levels&lt;/i&gt; without worrying about losing data.  As a result, we can transform the collect&amp;#8217;s into inject&amp;#8217;s and build the array from the inside out.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class &amp;lt;&amp;lt; self
  def approved_expenses_for( panel_id )
    for_panel( panel_id ).for_state( 'approved' )
  end

  def build_expense_summary( expenses )
    expenses.group_by(&amp;amp;:pay_type).inject({}) |final_expenses, (pay_type, expenses_by_pay_type)|
      package = expenses_by_pay_type.group_by(&amp;amp;:payable_to).inject({}) do |temp_expenses, (payable_to, pay_to_expenses)|
        payment_amount = pay_to_expenses.map(&amp;amp;:amount).sum
        payment_count = pay_to_expenses.size
        expense_package = self.financial_transaction_package(pay_type, payable_to, payment_amount, payment_count, User.current_user.id, panel.court_id, court_ap_id)
        temp_expenses.merge( expense_package )
      end
      final_expenses.merge( package )
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The extra statements that the inject requires is making that a little cluttered.  Let&amp;#8217;s break the build_expense_summary up into two functions, one that builds the expenses by pay_type and another that builds the expenses by payable_to.  Since their scope is pretty specific we&amp;#8217;ll make them private, too.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
class &amp;lt;&amp;lt; self
  def approved_expenses_for( panel_id )
    for_panel( panel_id ).for_state( 'approved' )
  end

  private
  def build_expense_summary( expenses )
    expenses.group_by(&amp;amp;:pay_type).inject({}) |expense_package, (pay_type, expenses_by_pay_type)|
      package = build_financial_transaction_package_by_payable(pay_type, expenses)
      expense_package.merge( package )
    end
  end

  def build_financial_transaction_package_by_payable(pay_type, expenses)
    expenses.group_by(&amp;amp;:payable_to).inject({}) do |expense_package, (payable_to, pay_to_expenses)|
      payment_amount = pay_to_expenses.map(&amp;amp;:amount).sum
      payment_count = pay_to_expenses.size
      package = self.financial_transaction_package(pay_type, payable_to, payment_amount, payment_count, User.current_user.id, panel.court_id, court_ap_id)
      expense_package.merge( package )
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As constructed, build_expense_summary will return a hash.  Thus, with this refactoring we&amp;#8217;ve not only made the intention of the nested group_by calls more explicit we&amp;#8217;ve also eliminated the need for the less-common mode of Hash instantiation.  Nice.&lt;/p&gt;
&lt;p&gt;We have also substantially simplified the original complete_payment method.  The call to build up the set of expenses to process is wrapped up in a method and the processing of those expenses is also a method with an intention-revealing name.&lt;/p&gt;
&lt;p&gt;Before presenting the final result I&amp;#8217;ll also point out that I have a preference for methods that exit once they&amp;#8217;ve determined they&amp;#8217;ve reached their end.  In this case I would much prefer to return false when the HTTP request fails than to set a flag and exit later.&lt;/p&gt;
&lt;h2&gt;The Reveal&lt;/h2&gt;
&lt;pre&gt;&lt;code&gt;
class &amp;lt;&amp;lt; self
  def complete_payment( panel_id )
    panel = Panel.find(panel_id)
    court_ap_id = Court.find(panel.court_id).accounts_payable.id

    transaction do
      approved_expenses = approved_expenses_for panel_id
      expense_summary = build_expense_summary approved_expenses

      unless Journal.post_group_of_entries_with_summary_account(expense_summary, panel.court_id, User.current_user.id).is_a?(Net::HTTPOK)
        logger.debug("ERRORED in Journaling with #{resp.body}")
        raise ActiveRecord::Rollback
      end
    end
  end

  def approved_expenses_for( panel_id )
    for_panel( panel_id ).for_state( 'approved' )
  end

  private
  def build_expense_summary( expenses )
    expenses.group_by(&amp;amp;:pay_type).inject({}) |expense_package, (pay_type, expenses_by_pay_type)|
      package = build_financial_transaction_package_by_payable(pay_type, expenses)
      expense_package.merge( package )
    end
  end

  def build_financial_transaction_package_by_payable(pay_type, expenses)
    expenses.group_by(&amp;amp;:payable_to).inject({}) do |expense_package, (payable_to, pay_to_expenses)|
      payment_amount = pay_to_expenses.map(&amp;amp;:amount).sum
      payment_count = pay_to_expenses.size
      package = self.financial_transaction_package(pay_type, payable_to, payment_amount, payment_count, User.current_user.id, panel.court_id, court_ap_id)
      expense_package.merge( package )
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;The refactored code is both longer &lt;i&gt;and&lt;/i&gt; more concise.  Huh?  Well, in this case we&amp;#8217;ve actually added a half-dozen lines or so to the solution (counting comments and blank lines in each).  We&amp;#8217;ve also expanded one method into four.  In those senses the code is longer.  At the same time the methods that we have are significantly shorter with method names and additional variables used to make it more explicit.  The methods are more concise to read and easier to comprehend.  It&amp;#8217;s also more concise in the sense that at least one of the extracted methods will be reused elsewhere so the code as a whole is more concise.&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/342759099</link><guid>http://blog.andyvanasse.com/post/342759099</guid><pubDate>Tue, 19 Jan 2010 10:00:00 -0500</pubDate></item><item><title>New Year's Cleanup: Off Color Code</title><description>&lt;p&gt;For a number of reasons I have inherited a lot of code recently and I&amp;#8217;m in the process of trying to clean up and put the finishing touches on a release we hope to see out the door soon.  That&amp;#8217;s the good news.  The bad news is that my emphasis has had a lot more &amp;#8216;clean up&amp;#8217; than &amp;#8216;finishing touches&amp;#8217; of late.&lt;/p&gt;
&lt;h2&gt;What is Off-Color Code?&lt;/h2&gt;
&lt;p&gt;One of the things that I have had to clean up a fair bit of is off-color code.  What is off-color code?  It&amp;#8217;s that code in your repository that is impossible to decipher at first glance because no source code highlighter can help.  It looks something like this&amp;#8230;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
#    def complete_payment(panel_id)
#        Panel.transaction do
#          panel = Panel.find(panel_id)
#          court_ap_id = Court.find(panel.court_id).accounts_payable.id
#          # identify all pending expenses for the panel
#          pending_expenses = Financial::RosterExpense.for_panel(panel_id).for_state('approved')
#          # collect hash fo summarized rosters to send for journalling to financials
#          ...snip a few dozen lines...
#          unless resp.instance_of?(Net::HTTPOK)
#            logger.debug("ERRORED in Journaling with #{resp.body}")
#            raise ActiveRecord::Rollback
#            response = false
#          end
#        end
#        response ||= true
#        return response
#      end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The syntax highlighting on this site cannot even help there.  What&amp;#8217;s that?  It&amp;#8217;s all comments?  Exactly.  It&amp;#8217;s all comments.&lt;/p&gt;
&lt;p&gt;The uncertain developer prefers to keep deprecated code in the code base while refactoring.  He fears the code surgeon&amp;#8217;s scalpel when performing a long overdue operation. Why?  Most often there is a sense that if the code is removed completely then some &amp;#8216;knowledge&amp;#8217; has been lost or we might forget some insight we once had.&lt;/p&gt;
&lt;p&gt;Wrong.  Don&amp;#8217;t comment out code.  That&amp;#8217;s what git, subversion, cvs, and all the other source code management software is for.  Cut the dead code loose from your code base.  You will not miss it.  Ever.  If you doubt it then try the following test.&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;Open a project that is old enough to eat solid food.&lt;/li&gt;
&lt;li&gt;Find a model or controller that has a method (or at least a large chunk of contiguous code) commented out.&lt;/li&gt;
&lt;li&gt;Summarize what the code does in less than ten seconds. (1pt)&lt;/li&gt;
&lt;li&gt;Name at least one insight contained in the code. (1pt each)&lt;/li&gt;
&lt;li&gt;Count the number of times you have read the code in the last month (1pt each).&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;If you score 1 point or less then it&amp;#8217;s time to get rid of that code.&lt;/p&gt;
&lt;h2&gt;The Cost of Dead Code&lt;/h2&gt;
&lt;p&gt;The biggest problem with dead code is that it has a larger cost than benefit.  The cost is measured in a few ways.  It takes away from your code base by making it more difficult to read and comprehend the &lt;i&gt;active&lt;/i&gt; code because you have to skip around it.  It takes away from your code by adding to the questions that brought you to this particular code: is this code coming or going?  Has it been recaptured elsewhere?  Why was it removed in the first place?&lt;/p&gt;
&lt;p&gt;Simply put, this code in suspended animation takes your eye away from what your source is otherwise trying to accomplish.  Even worse, it does this every time you look at the source code.&lt;/p&gt;
&lt;p&gt;Get rid of that dead code.&lt;/p&gt;
&lt;p&gt;Simplify.  &lt;strike&gt;Simplify.&lt;/strike&gt; &lt;strike&gt;Simplify.&lt;/strike&gt;&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/334397084</link><guid>http://blog.andyvanasse.com/post/334397084</guid><pubDate>Thu, 14 Jan 2010 13:07:00 -0500</pubDate></item><item><title>Conditionally absolute</title><description>&lt;p&gt;I like footers, well, that appear at the foot of the page.  I guess that seems obvious enough  but what I really mean is a bit more specific.  If I have a &amp;#8216;short&amp;#8217; page in which the page content only extends halfway down the bottom of the browser window (viewport) then I want the footer pushed to the bottom of the viewport.  If I have a &amp;#8216;long&amp;#8217; page where the content scrolls past the bottom of the viewport then the footer should just appear at the end of the content.&lt;/p&gt;
&lt;p&gt;I could probably wait for the footer tag coming in HTML 5.  I do not know, however, if rendering engines will widely adopt &lt;i&gt;my&lt;/i&gt; wishes for footer placement.  Moreover, I don&amp;#8217;t particularly care to wait for widespread implementation of HTML5 across browsers, particularly those &amp;#8216;non-modern&amp;#8217; browsers that are likely to dominate my user base.  I need the answer now.&lt;/p&gt;
&lt;h2&gt;Absolute positioning&lt;/h2&gt;
&lt;p&gt;Absolute positioning would seem to be a great answer.  But it&amp;#8217;s not.  I tried the following (haml/sass):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
#footer{:style=&amp;gt;'position: absolute; bottom: 0;'}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This solution worked very well for the &amp;#8216;short&amp;#8217; page on which I first tested it and I was actually pretty happy with it.  The page renders with blank space between the end of the content and the nearly-black 3em footer.  The problem is that it had the exact opposite effect of not positioning the footer absolutely.  Specifically, with long pages I now have the footer stuck in the middle of the content (rather than in the middle of a short page with blank space trailing the footer).  Back to the drawing board.&lt;/p&gt;
&lt;h2&gt;Conditional absolutes&lt;/h2&gt;
&lt;p&gt;Really I had the two pieces that I needed in place.  For long pages I could let the footer stay in place at the end of the content.  For short pages I could force it to the bottom of the viewport.  If only I could switch between the two&amp;#8230;&lt;/p&gt;
&lt;p&gt;Which of course I could, with jquery.  Actually it took jquery and an additional class on the footer div.  The styling for the additional class contains the style that I was applying inline above.  Specifically: (sass)&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
#footer.floor
  :position absolute
  :bottom 0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Having created that simple class I then added the following jquery snippet to my $(document).ready function:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
    if ( $(window).height() &amp;gt; $('body').height() ) {
        $('#footer').addClass('floor');
    } else {
        $('#footer').removeClass('floor');
    }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This code simply compares the height of the &amp;#8216;body&amp;#8217; (the content) to the height of the viewport.  If the content is shorter than the viewport then we add the &amp;#8216;floor&amp;#8217; class to the footer, adding the absolute positioning to the bottom of the viewport for &amp;#8216;short&amp;#8217; pages.  If the content is longer than the viewport then we remove the &amp;#8216;floor&amp;#8217; class (just in case it had been added previously) and let the footer sit at the end of the content.&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/309771176</link><guid>http://blog.andyvanasse.com/post/309771176</guid><pubDate>Thu, 31 Dec 2009 09:47:46 -0500</pubDate><category>rails</category><category>css</category><category>sass</category><category>jquery</category></item><item><title>Spraying for Weeds</title><description>&lt;p&gt;&lt;img align="right" src="http://www.solousa.com/store/shop_image/product/5aba92d4fa4f85595402753f188c8b76.gif" alt="Solo backpack sprayer" width="175" height="250"/&gt;&lt;/p&gt;
&lt;h2&gt;What?  Really?&lt;/h2&gt;
&lt;p&gt;Yes, really.  It&amp;#8217;s the day after Christmas and I spent most of the afternoon spraying for weeds, blowing leaves, and doing other assorted yard cleanup tasks.  That probably seems a little bizarre to those of you who get to enjoy the kind of &amp;#8220;White Christmas&amp;#8221; that is only myth to the Upstate of South Carolina but where a winter day resembles some autumn mornings in New England it&amp;#8217;s okay.  Besides, it has its advantages.&lt;/p&gt;
&lt;p&gt;First, only hours removed from Christmas I can already tell that I need the exercise.  I enjoy yard work for that simple fact.  There&amp;#8217;s a pretty obvious, and some would say annual, resolution coming here for the New Year but that&amp;#8217;s a story for another day.&lt;/p&gt;
&lt;p&gt;Second, and more importantly, the time spent doing yard work is great time to think.  Lawn mowers, blowers, and their kin are great white noise generators that quickly fade into the background.  At the same time, the tools of the trade also create some distance for uninterrupted thought.&lt;/p&gt;
&lt;p&gt;Today&amp;#8217;s tour of the yard helped me finally knock out a task that has long been calling me: spraying for weeds.  Nearly half of our yard is consumed by mulch beds that seem to be very inviting to weeds.  With the busy schedule we had this fall the weeds gladly accepted the invitation and felt right at home.&lt;/p&gt;
&lt;h2&gt;Killing weeds in December&lt;/h2&gt;
&lt;p&gt;To combat the weeds I mixed some concentrated weed killer into my backpack sprayer and set out to the backyard.  The privacy fence beside the kids&amp;#8217; fort fell quickly as did the side yard that&amp;#8217;s primarily green space.  I felt a little cheated when I got to the front yard.  There was a strong stand of weeds in the bed that we share with one of our neighbors.  I sprayed those weeds and followed them into the neighbors yard, cleaning up a bit of that as well.  I completed the circuit by knocking out the edge of the yard along the drive.  That was the part that bothered us the most &amp;#8212; we see it as we go in and out of the house.&lt;/p&gt;
&lt;p&gt;The advantage of taking care of weeds at this time of year is pretty simple: if it&amp;#8217;s green it&amp;#8217;s a weed.  Our bermuda lawn is dormant for the winter so we can spray weeds there without worrying about killing the grass.  The flower beds and gardens are similarly slumbering for the winter so those can also be cleaned up.  There is no &amp;#8220;pressure&amp;#8221; to keep up all the yard.  I can just concentrate on the weeds.&lt;/p&gt;
&lt;h2&gt;Spraying for Weeds = TDD&lt;/h2&gt;
&lt;p&gt;Naturally (pun intended), spraying for weeds led my thoughts to Test Driven Development (TDD).  Spraying for weeds in December is similar to TDD in that I get to concentrate on how the lawn &lt;i&gt;should&lt;/i&gt; look.  I can define the outline of the bed without worrying about the side effects of the weed killer (it has a tendency to hurt the runners in bermuda grass and leave odd looking yellow streaks in the lawn).  Cleaning up the beds during December isolates me from the &amp;#8220;pressure&amp;#8221; of caring for the whole active yard.  In a similar way TDD allows me to concentrate on a particular piece of the overall puzzle without the &amp;#8220;pressure&amp;#8221; of working a quick fix for an effected customer.&lt;/p&gt;
&lt;h2&gt;Staying focused&lt;/h2&gt;
&lt;p&gt;The side trip into my neighbors&amp;#8217; yard also has some implications on TDD.  On projects that involve more than one developer &amp;#8212; that is &lt;i&gt;most&lt;/i&gt; software of consequence &amp;#8212; you&amp;#8217;ll often find yourself &amp;#8220;sidetracked&amp;#8221; into your neighbor&amp;#8217;s code while tracing out functionality.  In these situations it&amp;#8217;s often best to touch only that part of the code that directly impacts your own.  For my own part I sprayed only that part of the bed that touched my yard &lt;i&gt;and&lt;/i&gt; had weeds.  Why?  Because I only had a certain amount of weed killer and I needed to make sure that I used it to focus on my yard first.  In truth I finished up my yard with some weed killer to spare so I returned to my neighbors adjoining bed and sprayed as far as the weed killer would take me.  In a similar way, development time is limited.  By concentrating on a particular part of the code base and tracing the code in question into other parts of the code base &lt;i&gt;but only as far as they impact the code in question&lt;/i&gt; you keep one primary thought in mind and typically solve it more quickly.  You can always return to &amp;#8220;the scene of the crime&amp;#8221; and clean it up with tests in the future!&lt;/p&gt;
&lt;h2&gt;But Weeds and Bugs Still Follow&lt;/h2&gt;
&lt;p&gt;Another thought occurred to me about TDD while spraying those weeds: next spring other weeds will eventually grow.  Some have criticized the TDD movement over assertions that it&amp;#8217;s ineffective because it does not prevent bugs.  That charge is an over-reaction to blind faith assertions of TDDers that TDD produces bug-free code.  In reality neither is true.&lt;/p&gt;
&lt;p&gt;Software represents our best understanding of the problem and its solution at a point in time.  In TDD this knowledge is captured both in the code used by the user and the test cases that outline the requirements.  As the days pass, nuances of the problem will reveal themselves and unconsidered edge cases will arise.  In some cases this is reported as a &amp;#8220;bug&amp;#8221; &amp;#8212; and from the user&amp;#8217;s perspective it probably is because the software as designed did not meet their expectations.  This is a natural cycle in software development.  When applied correctly, TDD accounts for the new &amp;#8220;weeds&amp;#8221; in the code base in the same way as the original &amp;#8220;weeds&amp;#8221;.  New tests are created to describe the additional information about the problem domain and new methods are added to solve it.  So with TDD we do not simply assume that the weeds will never arise; we apply the same method and deal with the weeds if and when they do arise.&lt;/p&gt;
&lt;p&gt;From our neighbors&amp;#8217; yard, of course.&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/301795760</link><guid>http://blog.andyvanasse.com/post/301795760</guid><pubDate>Sat, 26 Dec 2009 18:00:15 -0500</pubDate><category>tdd</category></item><item><title>When is it time to refactor?
It’s time to refactor legacy...</title><description>&lt;img src="http://24.media.tumblr.com/tumblr_kutcyu6lsp1qa9gn2o1_500.png"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;When is it time to refactor?&lt;/h2&gt;
&lt;p&gt;It’s time to refactor legacy code when… you see a rainbow and not the code.&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/287862414</link><guid>http://blog.andyvanasse.com/post/287862414</guid><pubDate>Thu, 17 Dec 2009 15:30:30 -0500</pubDate></item><item><title>A person can only be a novelty once, and only briefly, and charm, like any commodity, when used...</title><description>&lt;p&gt;A person can only be a novelty once, and only briefly, and charm, like any commodity, when used uneconomically becomes a wasting asset.&lt;/p&gt;
&lt;p&gt;- George Will, 17-Dec-2009&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/287522320</link><guid>http://blog.andyvanasse.com/post/287522320</guid><pubDate>Thu, 17 Dec 2009 09:15:00 -0500</pubDate></item><item><title>The UK’s best handheld for 40yrs (via UnrulyMediaChannel)</title><description>&lt;iframe width="400" height="300" src="http://www.youtube.com/embed/fVMnmTFxAjA?wmode=transparent&amp;autohide=1&amp;egm=0&amp;hd=1&amp;iv_load_policy=3&amp;modestbranding=1&amp;rel=0&amp;showinfo=0&amp;showsearch=0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;&lt;a href="http://www.youtube.com/watch?v=fVMnmTFxAjA"&gt;The UK’s best handheld for 40yrs&lt;/a&gt; (via &lt;a href="http://youtube.com/user/UnrulyMediaChannel"&gt;UnrulyMediaChannel&lt;/a&gt;)&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/269182374</link><guid>http://blog.andyvanasse.com/post/269182374</guid><pubDate>Fri, 04 Dec 2009 11:42:46 -0500</pubDate></item><item><title>I am the Keymaster, are you the Gatekeeper?</title><description>&lt;p&gt;&lt;img src="http://snarkerati.com/movie-news/files/2009/04/rick-moranis-ghostbusters.jpg" alt="Rick Moranis in Ghostbusters"/&gt;&lt;/p&gt;
&lt;p&gt;Several weeks ago I started writing an authorization gem on the way home from a weeks&amp;#8217; vacation.  The problem with the set of gems and plugins that I&amp;#8217;d used in the past were several.  One gem was much too tightly coupled to an authentication gem that I no longer used.  Others required too much wiring.  So, off I went to create the next great gem.  At least until I got home and ran into a stray question in a ruby forum about the DeclarativeAuthorization gem.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://github.com/stffn/declarative_authorization"&gt;DeclarativeAuthorization&lt;/a&gt; is the gem that I wished I&amp;#8217;d written for a number of reasons.  First, DeclarativeAuthorization is almost entirely self-contained from the rest of your application.  It&amp;#8217;s only requirement is that your user/account model support a collection of role_names.  How you support that collection is &lt;i&gt;entirely&lt;/i&gt; up to you.  That&amp;#8217;s the kind of separation that I really wanted and that ultimately had triggered my ideas for writing a gem in the first place.&lt;/p&gt;
&lt;p&gt;DeclarativeAuthorization uses a ruby script to define roles and to assign privileges to those roles.  The approach is simple and clean&amp;#8230; even when the rules for roles get murky.  There are two big advantages to this.  One is that the rules do not depend on any &amp;#8220;Rails magic&amp;#8221; or golden values in your database.  The other is that the roles and privileges can grow with your project regardless of the eventual complexity.&lt;/p&gt;
&lt;h2&gt;Composing Privileges&lt;/h2&gt;
&lt;p&gt;Out of the box DeclarativeAuthorization has a simple set of privilges for CRUD&amp;#8230; conveniently named Create, Read, Update, and Delete.  The privileges are declared as follows.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
privileges do
  privilege :manage, :includes =&amp;gt; [:create, :read, :update, :delete]
  privilege :read, :includes =&amp;gt; [:index, :show]
  privilege :create, :includes =&amp;gt; :new
  privilege :update, :includes =&amp;gt; :edit
  privilege :delete, :includes =&amp;gt; :destroy
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What&amp;#8217;s been really well thought out here is how privileges should be composed together.  For example, it seems fairly obvious at the UI level that in order to be able to &amp;#8216;update&amp;#8217; something you must first be able to &amp;#8216;edit&amp;#8217; it (at least in the Rails view of REST).  Similarly, DeclarativeAuth sensibly defines &amp;#8216;read&amp;#8217; as &amp;#8216;show&amp;#8217; and &amp;#8216;index&amp;#8217;.&lt;/p&gt;
&lt;p&gt;But what if you wanted to go a level higher?  For example, what if you have an admin area and you know that only admins should be able to perform any CRUD?  Won&amp;#8217;t it get annoying repeating tests for each aspect of CRUD?  Nope.  Because you can compose the privileges.  That&amp;#8217;s the essence of the first line of the block.  In that line we have a &amp;#8220;manage&amp;#8221; privilege that is defined to be the same as granting each individual C/R/U/D privilege.&lt;/p&gt;
&lt;h2&gt;Roles Compose, Too!&lt;/h2&gt;
&lt;p&gt;DeclarativeAuth also supports composing roles as well.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;
authorization do
  role :guest do
    has_permission_on :conferences, :to =&amp;gt; :read do
      if_attribute :published =&amp;gt; true
    end
    has_permission_on :talks, :to =&amp;gt; :read do
      if_permitted_to :read, :conference
    end
    has_permission_on :users, :to =&amp;gt; :create
    has_permission_on :authorization_rules, :to =&amp;gt; :read
    has_permission_on :authorization_usages, :to =&amp;gt; :read
  end
  
  role :user do
    includes :guest
    has_permission_on :conference_attendees, :to =&amp;gt; :create, :join_by =&amp;gt; :and do
      if_attribute :user =&amp;gt; is {user}
      if_permitted_to :read, :conference
    end
    has_permission_on :conference_attendees, :to =&amp;gt; :delete do
      if_attribute :user =&amp;gt; is {user}
    end
    has_permission_on :talk_attendees, :to =&amp;gt; :create do
      if_attribute :talk =&amp;gt; { :conference =&amp;gt; { :attendees =&amp;gt; contains {user} }},
          :user =&amp;gt; is {user}
    end
    has_permission_on :talk_attendees, :to =&amp;gt; :delete do
      if_attribute :user =&amp;gt; is {user}
    end
  end

  ...
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Obviously there&amp;#8217;s a *lot* going on in that code snippet.  The point here is found in the first line of the block for &amp;#8216;role :user do&amp;#8217; &amp;#8212; &amp;#8216;include :guest&amp;#8217;.  Simply put, the user gets to do everything that a guest can do plus what&amp;#8217;s defined in the rest of the block.  That makes for a very powerful and concise way to keep track of roles and privileges.&lt;/p&gt;
&lt;p&gt;Without getting into the details too much, the other thing to note in the definition of the :user role is the if_attribute calls.  if_attribute allows the role definition to move beyond global scope for the class and validate privileges on an instance by instance basis.  The if_attribute calls in the :user definition essentially say &amp;#8220;if the current user is the user associated with the instance (the one that created it) then the user can&amp;#8230;&amp;#8221;.&lt;/p&gt;
&lt;h2&gt;Integration across the Rails MVC stack&lt;/h2&gt;
&lt;p&gt;With the ability to set privileges based on attributes of a particular instance you may be thinking, &amp;#8220;Wow, I could use that to secure data at the instance level&amp;#8230;&amp;#8221;  You&amp;#8217;d be right.  And, of course, DeclarativeAuth already does that.&lt;/p&gt;
&lt;p&gt;DeclarativeAuth has a simple API that allows you to specify privileges in the models to secure access at the (data) class level in addition to the broader access control at the controller level.  There are even nice helpers available in the views to show/hide UI based on the privileges of the current user.&lt;/p&gt;
&lt;h3&gt;ConferenceAttendee data class&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;
class ConferenceAttendee &amp;lt; ActiveRecord::Base
  using_access_control
  
  belongs_to :user
  belongs_to :conference
  validates_presence_of :user, :conference
  validates_associated :user, :conference
end
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;ConferencesController#index&lt;/h3&gt;
&lt;pre&gt;&lt;code&gt;
def index
    # Only show conferences that the current user may read:
    @conferences = Conference.with_permissions_to(:read)
 
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml =&amp;gt; @conferences }
    end
  end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note: All the code snippets presented here come from the &lt;a href="http://github.com/stffn/decl_auth_demo_app"&gt;sample&lt;/a&gt; app for DeclarativeAuthorization&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/246139724</link><guid>http://blog.andyvanasse.com/post/246139724</guid><pubDate>Mon, 16 Nov 2009 11:44:01 -0500</pubDate><category>rails</category><category>authorization</category></item><item><title>Thinking Functionally in Ruby</title><description>&lt;a href="http://skillsmatter.com/podcast/ajax-ria/enumerators"&gt;Thinking Functionally in Ruby&lt;/a&gt;: &lt;p&gt;Tom Stuart introduces Functional Programming ideas to Ruby developers at a London Ruby User group meeting.  Great intro to FP with a reference to the most FP-like module in Ruby: Enumerable (and my personal fav Enumerable#inject).  Even if FP is not your thing it’s worth watching the video from around the 35 minute mark on to see the Ruby examples.&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/235240544</link><guid>http://blog.andyvanasse.com/post/235240544</guid><pubDate>Fri, 06 Nov 2009 15:34:51 -0500</pubDate></item><item><title>Wish I could fly Southwest to Toronto this week…</title><description>&lt;iframe width="400" height="300" src="http://www.youtube.com/embed/ivjybzdXVmI?wmode=transparent&amp;autohide=1&amp;egm=0&amp;hd=1&amp;iv_load_policy=3&amp;modestbranding=1&amp;rel=0&amp;showinfo=0&amp;showsearch=0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;Wish I could fly Southwest to Toronto this week…&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/221866997</link><guid>http://blog.andyvanasse.com/post/221866997</guid><pubDate>Sat, 24 Oct 2009 11:23:38 -0400</pubDate></item><item><title>Becoming a fan of MacVim
A few weeks ago some of my colleagues...</title><description>&lt;img src="http://24.media.tumblr.com/tumblr_krxk2fU7UD1qa9gn2o1_500.png"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;h2&gt;Becoming a fan of MacVim&lt;/h2&gt;
&lt;p&gt;A few weeks ago some of my colleagues through down the gauntlet: learn vim or give up lead dog status.  Not wanting to shrink from a challenge I decided to start playing with it and got hooked.&lt;/p&gt;
&lt;p&gt;The screenshot above shows one scenario in which (Mac)Vim really shines.  I really like the simplicity of setting up a split screen in vim.  When you’re trying to stick to a red-green-refactor cycle for developing business logic this layout is great.  Here I’ve got the spec on the left and the model on the right.  By sitting them side-by-side like this I don’t get quite as tempted to cheat the process, adding a bunch of code and then adding tests that pass, as I did in the singular view that I typically saw in most IDEs.&lt;/p&gt;
&lt;p&gt;The other aspect of the screenshot is down at the bottom.  A few keystrokes in Vim and you can execute command line stuff from within Vim.  So not only can I view the spec and the model it’s describing side-by-side but I can also run the test in place as well.  And in the event of a failure — which I &lt;i&gt;should&lt;/i&gt; have if I’m following the red-green-refactor approach properly — then I can see the failure, the spec that failed, and the class that failed.  Pretty powerful.&lt;/p&gt;
&lt;p&gt;The comment that really got me to try Vim was that it’s everywhere.  Well, okay, not &lt;i&gt;everywhere&lt;/i&gt; but it’s in all the environments that I need to use for development.  The MacVim release on my MBP is nice and stable.  Vim is, of course, alive and kicking on the Linux distros I’ve used for staging and production servers as well.  The rational was pretty simple: learn one tool and carry it with you everywhere.  That rational works for me.&lt;/p&gt;
&lt;h2&gt;Don’t miss Tim Pope’s Rails support&lt;/h2&gt;
&lt;p&gt;If you’re going to give MacVim a shot, make sure that you strongly look into the extensions that &lt;a href="http://github.com/tpope/"&gt;Tim Pope&lt;/a&gt; has constructed.  The vim-rails plugin is great for Rails developers.  For example, with vim-rails I can key “Rview accounts/show” and it opens up the &lt;b&gt;R&lt;/b&gt;ails &lt;b&gt;view&lt;/b&gt; for Accounts#show.  Tim’s also got plugins for haml and cucumber if you’re working with those, and recently added a wrapper for git.  Great stuff (not all of which I’ve been able to toy with but all worth a looksee.&lt;/p&gt;
&lt;h2&gt;So, what do I give up?&lt;/h2&gt;
&lt;p&gt;What you lose with Vim are some of the niceties of a traditional IDE.  Since I’ve only been using MacVim for a short while I have not found a project viewer like you’d have in TextMate and most IDEs.  Refactoring is a manual process… but in most Ruby IDEs that still true so you’re not sacrificing much if you can handle grep (from within Vim, of course!).&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/220202539</link><guid>http://blog.andyvanasse.com/post/220202539</guid><pubDate>Thu, 22 Oct 2009 15:13:27 -0400</pubDate></item><item><title>Best. Drink. Ever.</title><description>&lt;img src="http://25.media.tumblr.com/tumblr_krx38iT6Sn1qa9gn2o1_400.jpg"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;Best. Drink. Ever.&lt;/p&gt;</description><link>http://blog.andyvanasse.com/post/219962524</link><guid>http://blog.andyvanasse.com/post/219962524</guid><pubDate>Thu, 22 Oct 2009 09:09:53 -0400</pubDate></item><item><title>What's in a name?  Inject-ing your code</title><description>&lt;h2&gt;thoughts.inject(world)?&lt;/h2&gt;
&lt;p&gt;If you&amp;#8217;re new to Ruby you may not realize that the title to the blog is an ode to one of my favorite Ruby idioms: inject.  In a nutshell, inject is a customizable accumulator that Ruby mixes into collections through the Enumerable module (e.g., arrays and hashes).&lt;/p&gt;
&lt;h2&gt;Anatomy of an inject-ion&lt;/h2&gt;
&lt;p&gt;inject essentially has four parts: a collection to be iterated, a seed value, an accumulator, and a block used to &amp;#8216;accumulate&amp;#8217; the members of the collection.  In practice it looks something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class="Ruby"&gt;
collection.inject( seed_value ) do |accumulated_value, collection_member|
  accumulated_value.modify_by collection_member
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Given that structure, here&amp;#8217;s what happens&lt;/p&gt;
&lt;ol&gt;&lt;li&gt;accumulated_value is initialized with seed_value.&lt;/li&gt;
&lt;li&gt;accumulated_value and the first (second, third, &amp;#8230;) value of the collection is passed to the block.&lt;/li&gt;
&lt;li&gt;The result of executing the block &amp;#8212; the value returned by the last statement &amp;#8212; is assigned to accumulated_value.&lt;/li&gt;
&lt;li&gt;Repeat the previous two steps for every element of the collection.&lt;/li&gt;
&lt;li&gt;Return the last value assigned to accumulated_value.&lt;/li&gt;
&lt;/ol&gt;&lt;h2&gt;A simple example&lt;/h2&gt;
&lt;p&gt;The simplest, and probably canonical example, of using inject is to sum the values of an array.&lt;/p&gt;
&lt;pre&gt;&lt;code class="Ruby"&gt;
[1, 2, 3, 4, 5].inject( 0 ) do | total, value|
  total + value
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Just to be thoroughly pedantic, let&amp;#8217;s step through what&amp;#8217;s going on here based on the explanation above.  First, total is assigned the seed value of 0.  Next, 0 and the first value of the array (1) is passed to the block and the block evaluates total + value (0 + 1) and assigns it to total.  The next iteration passes that total (1) and the next value (2), performs the addition, and assigns 2+1=3 to total.  And so on.&lt;/p&gt;
&lt;p&gt;Now, if you&amp;#8217;re using Ruby to build a database-backed application this might seem to be a bit of a waste.  You can &lt;i&gt;and should&lt;/i&gt; delegate simple sums like this to the database and avoid the cost of returning the values, instantiating classes, and then reading the attributes you want to sum.  Databases live for that.  Let them.&lt;/p&gt;
&lt;h2&gt;A more practical example&lt;/h2&gt;
&lt;p&gt;In one app that I support we were discussing how to bill customers.  Stunning as it may be, that was a reasonably important issue for us so we wanted to get it right.  The application primarily provides member management support and billing is tied to the population of members.  The catch was that, at the current moment, both the member and the membership could be made inactive.  I&amp;#8217;m sure that there&amp;#8217;s a sql guy out there who&amp;#8217;s already got nested selects in mind but our app need only bill one time per month so we can afford to be a little less than optimal here.  Inject to the rescue.&lt;/p&gt;
&lt;pre&gt;&lt;code class="Ruby"&gt;
customer.memberships.inject(0) do |total, membership|
  membership.expired? ? total : total + membership.members.active.count
end
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So, what&amp;#8217;s going on?  It&amp;#8217;s really not that much more complicated than the sum example above.  As before we initialize the count with 0.  Next, we check each membership.  If the membership has expired then we just return the previously calculated total.  If not, we add the number of active members on the membership to the previously calculated total.&lt;/p&gt;
&lt;h2&gt;But wait, there&amp;#8217;s more!&lt;/h2&gt;
&lt;p&gt;There are two great things about inject that should not be overlooked.  First, the accumulator can accumulate in any way you want.  That means you can use it to &lt;i&gt;transform&lt;/i&gt; data as well.  For example, we could test to see how random random really is by checking to see how well it distributes numbers by using inject.&lt;/p&gt;
&lt;pre&gt;&lt;code class="Ruby"&gt;
numbers = []
1000.times{ numbers.push rand(4) }
numbers.inject( Hash.new(0) ){|frequencies, num| frequencies.merge num =&amp;gt; frequencies[num]+1}
=&amp;gt; {0=&amp;gt;254, 1=&amp;gt;249, 2=&amp;gt;248, 3=&amp;gt;249}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Furthermore, since inject is a method that gets mixed in from the Enumerable module that means you can use it far more widely than just arrays.  Hashes, strings, ranges&amp;#8230; you name it.  Anything that uses Enumerable can take advantage of inject.  Taking a variation on the number frequency above, what about finding the average length of a &amp;#8216;line&amp;#8217; in a string?&lt;/p&gt;
&lt;pre&gt;&lt;code class="Ruby"&gt;
str = "The quick\nbrown fox jumped\nover the lazy\ndog."
str.inject( Hash.new(0) ) do |lengths, line| 
  len = line.split(/\s+/).size
  lengths.merge len=&amp;gt;lengths[len]+1
end

=&amp;gt; {1=&amp;gt;1, 2=&amp;gt;1, 3=&amp;gt;2}
&lt;/code&gt;&lt;/pre&gt;</description><link>http://blog.andyvanasse.com/post/219624664</link><guid>http://blog.andyvanasse.com/post/219624664</guid><pubDate>Wed, 21 Oct 2009 22:58:00 -0400</pubDate><category>ruby</category><category>inject</category></item></channel></rss>

