Skip to content

Commit

Permalink
Make it possible to supply default serializer
Browse files Browse the repository at this point in the history
options in a controller.
  • Loading branch information
wycats committed Jan 12, 2012
1 parent 671fc14 commit 5564728
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
8 changes: 8 additions & 0 deletions lib/action_controller/serialization.rb
Expand Up @@ -36,13 +36,21 @@ def serialization_scope
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
end

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
Expand Down
16 changes: 15 additions & 1 deletion test/serialization_test.rb
Expand Up @@ -22,6 +22,7 @@ def initialize(object, options={})
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

Expand Down Expand Up @@ -109,6 +110,13 @@ def render_json_with_serializer_api_but_without_serializer
@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
Expand All @@ -133,7 +141,6 @@ def test_render_json_render_to_string
assert_equal '[]', @response.body
end


def test_render_json
get :render_json_hello_world
assert_equal '{"hello":"world"}', @response.body
Expand Down Expand Up @@ -181,6 +188,13 @@ def test_render_json_with_serializer
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
Expand Down

0 comments on commit 5564728

Please sign in to comment.