Nick Kallen noted that the behavior of has_many_with_args can be accomplished using has_finder.

Too true!

Imagine a system in which Users send Whispers to one another. We would like to see Whispers scoped so that:

  • A User viewing their own Whispers should see all Whispers they have received

  • A User viewing another User’s Whispers should see only Whispers they themselves sent

With the clean chainable syntax provided by has_finder, this is straight-forward. We return associations directly (notice, no find calls) and isolate declaration of the scoping the behavior to the class affected by it.

class Whisper < ActiveRecord::Base
  has_finder :from, lambda { |sender| { :conditions => [ 'sender_id = ?', sender.id ] } }
end
 
class User < ActiveRecord::Base
  has_many :received_whispers, :foreign_key => 'recipient_id'
 
  def whispers_viewable_by user
    return whispers if self == user
    whispers.from(user)
  end
end

How expressive is that? Business rules are cleanly captured in the models and our associations stay so limber!

Thanks to Pat Maddox for turning me on to has_finder, and Nick Kallen for writing it.

class Fixnum
  def clip_to range
    r = range.first < range.last ? range : (range.last)..(range.first)
    return [ [ r.min, self ].max, r.max ].min
  end
end

Updatehas_finder accomplishes everything has_many_with_args does in an elegant and extensible fashion. As it’s slated for inclusion in Rails 2.1, I thought I’d describe how to accomplish the scoped whispers example presented in this post using has_finder.

Read the solution here.

Rails Associations are powerful tools, but sometimes they can be a bit over-reaching.

Let’s examine a hypothetical has_many association and how it would traditionally be managed.

class User
  has_many :sent_whispers, :class_name => 'Whisper', :foreign_key => 'sender_id'
  has_many :received_whispers, :class_name => 'Whisper', :foreign_key => 'recipient_id'
end
 
class Whisper
  belongs_to :sender, :class_name => 'User'
  belongs_to :recipient, :class_name => 'User'
end

Now, if you’d like to scope down received whispers to just those sent by a specific user, you’d ordinarily probably use something along these lines.

def whispers_from sender
  with_scope( :find => { :conditions => [ 'sender_id = ?', sender.id ] } ) do
    received_whispers.find(:all)
  end
end

Unfortunately, this is pretty limiting. For example, any association extensions defined on :received_whispers are unavailable when accessing whispers_from. We also lose out on all the association calculation methods and can no longer use << to insert new elements directly into the association.

We could get the type of focused behavior we wanted by adding a conditions clause to the association.

has_many :whispers_from,
  :class_name => 'Whisper',
  :foreign_key => 'recipient_id',
  :conditions => [ 'sender_id = ?', sender.id ]

This won’t work either! sender isn’t defined in the class scope as the association is being created, so the conditions clause is at a loss. But all is not lost! A poorly-documented feature of the association methods is the lazy evaluation of conditions.

has_many :whispers_from,
  :class_name => 'Whisper',
  :foreign_key => 'recipient_id',
  :conditions => 'sender_id = #{sender.id}'

Notice that the conditions clause is singly-quoted. When the conditions clause is evaulated, the sender method will be called on the User. Better, but still not much use to us, as the User doesn’t have a sender method. Well, what if sender were an ordinary attr_reader on the User? If we could get @sender set prior to the evaluation of the association conditions, we’d be set!

Okay, we can do this!
I whipped up has_many_with_args (suggestions for a better name?) which allows you to create an association with teeth!

class User
  has_many_with_args :whispers_from, :sender,
    :class_name => 'Whisper',
    :foreign_key => 'recipient_id',
    :conditions => 'sender_id = #{sender.id}'
end

And that’s it! Now you can use all the regular has_many association methods, calculation methods, and your own association extensions. Boss!

alice = User.find(1)
bob = User.find(2)
alice.whispers_from(bob).count # SELECT COUNT(*) FROM users WHERE recipient_id=1 AND sender_id=2

It’s all packaged up as a plugin for you. Just install using piston:

piston import http://hasmanywithargs.googlecode.com/svn/trunk/ vendor/plugins/has_many_with_args

For the brave and curious, have a look at the source to see how the attr_readers are set up and initialized when the association is accessed.

Displaying ads on a site can be a little tricky. Many ad networks simply provide you with a snippet of javascript that must be embedded directly into a page where an ad is to be displayed. These often use document.write to generate more script tags which in turn may generate the actual ad content.

Regardless, sourcing external javascript files in this way can lead to choppy page loads as progressive rendering halts, waiting for this external content to be downloaded and evaluated. Yahoo!’s YSlow grades a page down for this, specifically for violation of Rule 6: Put Scripts at the Bottom.

With scripts, progressive rendering is blocked for all content below the script. Moving scripts as low in the page as possible means there’s more content above the script that is rendered sooner.

In some situations it’s not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page’s content, it can’t be moved lower in the page.

This was causing us serious pains as our ad-provider sometimes responded slowly, and sometimes responded not-at-all. In the spirit of graceful degradation, I crafted this solution for Rails.

Instead of generating the ad markup where the ad was supposed to appear, I first generate a placeholder DOM node, and using a content_for block, tuck the actual markup away. In the application’s layout template (application.rhtml), the last 3 lines are like so.

<%= yield :support_footer %>
  </body>
</html>

Generating the support_footer is straight-forward:

module DeferredContentInsertionHelper
 
  def deferred_insertion to_insert, options = {}
    content = case to_insert
    when String
      to_insert
    when Hash
      render_to_string(to_insert)
    end
 
    container = "di_#{content.hash}"
    defer_container = "defer_#{container}"
 
    content_for :support_footer do
      [ content_tag('div', content, :id => defer_container),
        javascript_tag("$('#{container}').parentNode.replaceChild($('#{defer_container}'), $('#{container}'));")
      ].join
    end
 
    # Insert a placeholder that the real content will replace once its loaded
    content_tag('span', '', :id => container)
  end
 
end

Now, when I want to generate an ad in the layout, instead of issuing:

<%= render :partial => 'ads/banner' %>

I can issue a deferred insertion and get a much more responsive page:

<%= deferred_insertion :partial => 'ads/banner' %>

Note how content generated in the support_footer is initially hidden, and is shown after it has been moved into place.

We were experiencing issues with ads being initially hidden and then moved into place. By leaving them visible, they render properly. The page layout changing as elements are added and removed can be overcome with appropriate css sizing.

I recently posted on determining whether two arrays contain the same elements irrespective of ordering.

The approach supplied works for some basic Ruby types, but failed for complex types such as arrays of instances of custom classes.

class Foo
  attr_accessor :i
 
  def initialize new_i
    self.i = new_i
  end
 
  def == another_foo
    self.i == another_foo.i
  end
 
end
 
foo1 = Foo.new(1)
foo2 = Foo.new(1)
 
[ foo1 ].same_elements?( [ foo2 ] ) # Expected true, got false

The culprit lay in Ruby’s Hash equality comparison method. In the original implementation of same_elements? a hash was built for each array. This hash’s keys were the unique elements of the array and its values were the counts of the number of occurrences of that key within the parent array.

Unfortunately, this led to the final comparison:

foo1 == foo2 # true
{ foo1 => 1 } == { foo2 => 1 } # false

To overcome this, we had to compare keys and values individually instead of with the built-in hash comparison.

class Array
  # Ask an Array whether it shares the same elements with another Array, irrespective of order
  # Options
  # :allow_duplicates
  #   If set to true arrays with the same elements, but differing numbers of those elements
  #   are treated as the same.
  #   Examples
  #     [ :a ].same_elements?( [ :a, :a ] ) => false
  #     [ :a ].same_elements?( [ :a, :a ], :allow_duplicates => true) => true
  def same_elements? another_array, options = {}
    raise ArgumentError, "#{another_array.inspect} was expected to be an Array" unless another_array.kind_of?(Array)
    s = self
    a = another_array
    if options[:allow_duplicates]
      s = s.uniq
      a = a.uniq
    end
 
    return element_counts(s) == element_counts(a)
  end
 
  private
    def element_counts obj
      result = []
      obj.uniq.map { |e|
        [ e, obj.inject(0) { |i, e2| i + (e == e2 ? 1 : 0 ) } ]
      }.each { |p| result << p.first; result << p.last }
 
      HashEqualityChecker.new(Hash[ *result ])
    end
end
 
class HashEqualityChecker < Hash
  def initialize new_hash
    self.replace new_hash
  end
 
  def == another_hash_equality_checker
    return false unless another_hash_equality_checker.size == size
 
    another_hash_equality_checker.inject(true) do |still_same, kv_pair|
      ak, av = kv_pair
 
      match = select do |k, v|
        k == ak && v == av
      end
 
      found_match = !match.empty?
      still_same && found_match
    end
  end
 
end

Now instead of using a default Hash for the element counts, we use the new HashEqualityChecker, which performs a == comparison on each pair of elements in the underlying Hash.