Permalink
Browse files

Initial commit of serializer support

  • Loading branch information...
1 parent 098c95a commit 8ff7693a8dc61f43fc4eaf72ed24d3b8699191fe @wycats wycats committed Sep 26, 2011
@@ -31,6 +31,7 @@ module ActionController
autoload :RequestForgeryProtection
autoload :Rescue
autoload :Responder
+ autoload :Serialization
autoload :SessionManagement
autoload :Streaming
autoload :Testing
@@ -190,6 +190,7 @@ def self.without_modules(*modules)
Redirecting,
Rendering,
Renderers::All,
+ Serialization,
ConditionalGet,
RackDelegation,
SessionManagement,
@@ -0,0 +1,26 @@
+module ActionController
+ module Serialization
+ extend ActiveSupport::Concern
+
+ include ActionController::Renderers
+
+ included do
+ class_attribute :_serialization_scope
+ end
+
+ def serialization_scope
+ send(_serialization_scope)
+ end
+
+ def _render_option_json(json, options)
+ json = json.active_model_serializer.new(json, serialization_scope) if json.respond_to?(:active_model_serializer)
+ super
+ end
+
+ module ClassMethods
+ def serialization_scope(scope)
+ self._serialization_scope = scope
+ end
+ end
+ end
+end
@@ -15,9 +15,32 @@ def to_json(options = {})
end
end
+ class JsonSerializer
+ def initialize(object, scope)
+ @object, @scope = object, scope
+ end
+
+ def as_json(*)
+ { :object => @object.as_json, :scope => @scope.as_json }
+ end
+ end
+
+ class JsonSerializable
+ def active_model_serializer
+ JsonSerializer
+ end
+
+ def as_json(*)
+ { :serializable_object => true }
+ end
+ end
+
class TestController < ActionController::Base
protect_from_forgery
+ serialization_scope :current_user
+ attr_reader :current_user
+
def self.controller_path
'test'
end
@@ -61,6 +84,11 @@ def render_json_with_extra_options
def render_json_without_options
render :json => JsonRenderable.new
end
+
+ def render_json_with_serializer
+ @current_user = Struct.new(:as_json).new(:current_user => true)
+ render :json => JsonSerializable.new
+ end
end
tests TestController
@@ -132,4 +160,10 @@ def test_render_json_calls_to_json_from_object
get :render_json_without_options
assert_equal '{"a":"b"}', @response.body
end
+
+ def test_render_json_with_serializer
+ get :render_json_with_serializer
+ assert_match '"scope":{"current_user":true}', @response.body
+ assert_match '"object":{"serializable_object":true}', @response.body
+ end
end
Oops, something went wrong.

0 comments on commit 8ff7693

Please sign in to comment.