TDD Persistence Without Any ORM

Here is simple tip how to make your data persisting between requests, without actually using any ORM, so, you can keep in focus on your domain model.

What problem with ORM?

ORM is semi-orthogonal to the business logic of your application. ORMs handle
the loading and saving of objects to records in a database. The behavior of
those objects, apart from persistence, is (theoretically) outside of the
ORM’s responsibilities

Singleton to rescue

Here is our simplest possible persistence layer :)

1
2
3
# config/initializers/wallet.rb

THE_WALLET = Wallet.new

then somewhere else, for example in application controller…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

  # ...

  before_filter :init_wallet

  private

  def init_wallet
    @wallet = THE_WALLET
  end
end

Finally, whenever we’re using @wallet object, such as @wallet.add_cash(10), its state is persisting between requests, so, we can continue with acceptance testing easily.

Further reading

Objects on Rails

Comments