Skip to content

Instantly share code, notes, and snippets.

@ivanyv
Created March 17, 2012 04:40
Show Gist options
  • Save ivanyv/2054991 to your computer and use it in GitHub Desktop.
Save ivanyv/2054991 to your computer and use it in GitHub Desktop.
Easy peasy serializer separation for DDD
# app/controllers/users_controller.rb
class UsersController < ApplicationController
respond_to :json, :xml
def show
@user = @user.find(params[:id])
respond_with Serializer(@user)
end
end
# app/models/user/serialize.rb
class User::Serialize < ::Serializer
def as_json(options = {})
@object.as_json({ ... }.merge(options))
end
def to_xml(options = {})
...
end
end
# lib/serializer.rb
class Object
def Serializer(object)
serializer = object.class.const_get('Serialize') rescue nil
serializer ? serializer.new(object) : object
end
end
class Serializer
def initialize(object)
@object = object
end
def method_missing(m, *args, &block)
@object.respond_to?(m) ? @object.send(m, *args, &block) : super
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment