Created
March 17, 2012 04:40
-
-
Save ivanyv/2054991 to your computer and use it in GitHub Desktop.
Easy peasy serializer separation for DDD
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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