Mikey

written by stonean on May 5th, 2008 @ 05:58 PM

So, I have a site that synchronizes data with another server. It does this via after_create, after_update and after_delete triggers on some models. All of those triggers use the same method that returns a connection object which has various methods such as:

  # SyncServer::connection method
  module SyncServer
    def self.connection
     new_client.connection{|conn| yield conn }
    end
  end

  SyncServer::connection do |conn|
    conn.add_person(person_data)
    # or
    conn.update_person(person_data)
    # or
    conn.delete_person(person_id)
  end
  
  # The following is to demonstrate I could have
  # multiple types of data I'm syncing
  # and therefore multiple methods on the
  # conn object.

  SyncServer::connection do |conn|
    conn.add_other_data(other_data)
    conn.modify_other_data(other_data)
    conn.delete_data(other_id)
  end

While the RSpec tests were running, these triggers were being called which was junking up the SyncServer. This is not cool. In order to avoid this, I needed to be able to disable the synchronization. I definitely didn't want to do this in all my triggers.

Enter Mikey, he's going to replace the conn object I return:

#
# Because Mikey will eat anything
#
class Mikey
  def method_missing(method, *args)
    true
  end
end

Now the new conn method:

  module SyncServer
    def self.connection
     if sync?
      new_client.connection{|conn| yield conn }
     else
      yield Mikey.new
     end
    end
  end

The sync? method just checks if the class variable do_synchronization is true. I set this class variable to false if the RAILS_ENV == test. The result is my triggers don't break, the sync server isn't junked up and my tests pass. All good.

Comments

  • Joseph HALTER on 20 Jul 15:16

    It seems like Mikey could grown into a fully grown acts_as_chuck_norris plugin!
  • Andy on 22 Jul 07:38

    That would be cool and the name alone would make it popular. :)

Post a comment