#972 suggestion
Ashley Moran

Specify modules to mix in to association Collection objects

Reported by Ashley Moran | July 14th, 2009 @ 03:26 PM

Recently today we ran against another frustration of mine: that you aren't in control of the class created for associations.

The specific situation was we have two models that have collections we need to manipulate by swapping elements. There was a lot of duplicated logic that is hard to factor out, because the names of everything are different.

What I'd really like to do is this:

class Parent
  include DataMapper::Resource

  # ...

  has n, :kids, :include => Swappable                    # or maybe...
  has n, :kids, :include_modules => [Swappable]          # or maybe...
  has n, :kids, :collection_class => SwappableCollection # ?
end

The solution we came up with was this:

module CollectionExtensions
  # If a swap occurred, returns the element swapped with.
  # If no swap occurred, returns the original element
  def swap(original_element, offset)
    original_element_index = index(original_element)
    swap_with_element_index = original_element_index + offset
    swap_with = self[swap_with_element_index]
    
    self[original_element_index], self[swap_with_element_index] = swap_with, original_element if (0...size).include?(swap_with_element_index)
    self[original_element_index]
  end
end

Merb::BootLoader.before_app_loads do
  module DataMapper
    class Collection
      include CollectionExtensions
    end
  end
end

I think just being able to do it with modules is enough. Supplying you own collection class may be too heavy, and not give any benefits.

But anyway, anyone got any thoughts?

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

People watching this ticket

Pages