Skip to content

Commit

Permalink
Enumerable should pass encoding options to children in #as_json/#to_j…
Browse files Browse the repository at this point in the history
…son.
  • Loading branch information
John Firebaugh committed Apr 1, 2011
1 parent 0eb6e5e commit 080e2a7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 10 deletions.
4 changes: 3 additions & 1 deletion activesupport/lib/active_support/json/encoding.rb
Expand Up @@ -205,7 +205,9 @@ def as_json(options = nil) to_s end #:nodoc:
end end


module Enumerable module Enumerable
def as_json(options = nil) to_a end #:nodoc: def as_json(options = nil) #:nodoc:
to_a.as_json(options)
end
end end


class Array class Array
Expand Down
33 changes: 24 additions & 9 deletions activesupport/test/json/encoding_test.rb
Expand Up @@ -215,6 +215,30 @@ def test_array_should_pass_encoding_options_to_children_in_to_json
assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json) assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
end end


def test_enumerable_should_pass_encoding_options_to_children_in_as_json
people = [
{ :name => 'John', :address => { :city => 'London', :country => 'UK' }},
{ :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
]
json = people.each.as_json :only => [:address, :city]
expected = [
{ 'address' => { 'city' => 'London' }},
{ 'address' => { 'city' => 'Paris' }}
]

assert_equal(expected, json)
end

def test_enumerable_should_pass_encoding_options_to_children_in_to_json
people = [
{ :name => 'John', :address => { :city => 'London', :country => 'UK' }},
{ :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
]
json = people.each.to_json :only => [:address, :city]

assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
end

def test_struct_encoding def test_struct_encoding
Struct.new('UserNameAndEmail', :name, :email) Struct.new('UserNameAndEmail', :name, :email)
Struct.new('UserNameAndDate', :name, :date) Struct.new('UserNameAndDate', :name, :date)
Expand Down Expand Up @@ -259,12 +283,3 @@ def with_env_tz(new_tz = 'US/Eastern')
old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ') old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end end
end end

class JsonOptionsTests < Test::Unit::TestCase
def test_enumerable_should_passthrough_options_to_elements
value, options = Object.new, Object.new
def value.as_json(options) options end
def options.encode_json(encoder) self end
assert_equal options, ActiveSupport::JSON.encode(value, options)
end
end

0 comments on commit 080e2a7

Please sign in to comment.