Skip to content

Instantly share code, notes, and snippets.

@kurko
Created February 8, 2012 19:52
Show Gist options
  • Save kurko/1772819 to your computer and use it in GitHub Desktop.
Save kurko/1772819 to your computer and use it in GitHub Desktop.
UoW
# If you've been in a medium to large project, you know how painful
# it becomes to maintain your domain logic in ActiveRecord files.
#
# Later you extract classes to lib/, so now you have a) domain logic
# classes and b) persistence objects (ActiveRecord). This means you
# started using the DataMapper pattern.
#
# Below is the draft for a gem to implement DataMapper pattern in Ruby.
# The Unit of Work pattern stands as an observer - whenever the domain
# object changes, the UoW saves its attributes to the database.
#
# See:
# DataMapper pattern: http://martinfowler.com/eaaCatalog/dataMapper.html
# Unit of Work pattern: http://martinfowler.com/eaaCatalog/unitOfWork.html
# Domain objects
class User
# this class should have nothing related to the dm layer
end
class Post
def initialize(attributes)
# save attributes
owner = attributes[:user] # triggers UoW
end
end
# Mapper objects
class UserMapper
attributes :name, :age, :bio
# ...rest of the code, like calling the ORM for saving
end
class PostMapper
attributes :title
attribute :owner, is: User
end
# Domain logic POROs. UoW objects' responsibility is to save data under the hood automatically
class UsersController < ApplicationController
def create
@user = User.new(name: "Alexandre", age: 24) # should UoW persist at this point?
@page = Page.new(title: "A title", owner: @user) # should UoW persist at this point?
end
end
# Persistence alternatives:
#
# 1. UoW saves data upon app instance termination (DataMapper would be a middleware)
# 2. Domain objects has #persist method, i.e @user.persist, which calls uow.save. I personally don't like this approach that much.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment