Make it possible to supply default serializer

options in a controller.
This commit is contained in:
Yehuda Katz 2012-01-11 21:30:10 -07:00
parent 671fc14888
commit 55647286da
2 changed files with 23 additions and 1 deletions

View File

@ -36,6 +36,9 @@ module ActionController
send(_serialization_scope)
end
def default_serializer_options
end
def _render_option_json(json, options)
if json.respond_to?(:to_ary)
options[:root] ||= controller_name
@ -43,6 +46,11 @@ module ActionController
if json.respond_to?(:active_model_serializer) && (serializer = json.active_model_serializer)
options[:scope] = serialization_scope
if default_options = default_serializer_options
options = options.merge(default_options)
end
json = serializer.new(json, options)
end
super

View File

@ -22,6 +22,7 @@ class RenderJsonTest < ActionController::TestCase
def as_json(*)
hash = { :object => serializable_hash, :scope => @options[:scope].as_json }
hash.merge!(:options => true) if @options[:options]
hash.merge!(:check_defaults => true) if @options[:check_defaults]
hash
end
@ -109,6 +110,13 @@ class RenderJsonTest < ActionController::TestCase
@current_user = Struct.new(:as_json).new(:current_user => true)
render :json => JsonSerializable.new(true)
end
private
def default_serializer_options
if params[:check_defaults]
{ :check_defaults => true }
end
end
end
tests TestController
@ -133,7 +141,6 @@ class RenderJsonTest < ActionController::TestCase
assert_equal '[]', @response.body
end
def test_render_json
get :render_json_hello_world
assert_equal '{"hello":"world"}', @response.body
@ -181,6 +188,13 @@ class RenderJsonTest < ActionController::TestCase
assert_match '"object":{"serializable_object":true}', @response.body
end
def test_render_json_with_serializer
get :render_json_with_serializer, :check_defaults => true
assert_match '"scope":{"current_user":true}', @response.body
assert_match '"object":{"serializable_object":true}', @response.body
assert_match '"check_defaults":true', @response.body
end
def test_render_json_with_serializer_and_implicit_root
get :render_json_with_serializer_and_implicit_root
assert_match '"test":[{"serializable_object":true}]', @response.body