Skip to main content

Card persistence with lambdas

The basic idea:

class Card
  def initialize(id, persistence_callback)
    @id = id
    @persistence_callback = persistence_callback
  end

  def commit
    @persistence_callback.call(self)
  end
end

class Factory
  def do_persistence(card)
    # implementation goes here
  end

  def create_card
    callback = lambda { |card| self.do_persistence(card) }
    card = Card.new(get_new_card_id(), callback)
  end
end

The idea is that an individual card doesn't need a handle to its persistence engine - and indeed nothing else does. It just needs a proc that it can invoke to perform persistence. This could be changed at runtime - for example, migrating a mud object from one server to another consists of "persisting" it across a network.

Understanding the operation becomes easier, however, if we don't think of it so much as persistence and more like shuffling a card into a new deck.