lib/active_support/json/encoders/hash.rb in activesupport-2.3.2 vs lib/active_support/json/encoders/hash.rb in activesupport-2.3.3
- old
+ new
@@ -1,5 +1,7 @@
+require 'active_support/core_ext/array/wrapper'
+
class Hash
# Returns a JSON string representing the hash.
#
# Without any +options+, the returned JSON string will include all
# the hash keys. For example:
@@ -26,21 +28,29 @@
# { :users => users, :count => users.size }.to_json(:include => :posts)
#
# would pass the <tt>:include => :posts</tt> option to <tt>users</tt>,
# allowing the posts association in the User model to be converted to JSON
# as well.
- def to_json(options = {}) #:nodoc:
- hash_keys = self.keys
+ def to_json(options = nil) #:nodoc:
+ hash = as_json(options)
- if except = options[:except]
- hash_keys = hash_keys - Array.wrap(except)
- elsif only = options[:only]
- hash_keys = hash_keys & Array.wrap(only)
- end
-
result = '{'
- result << hash_keys.map do |key|
- "#{ActiveSupport::JSON.encode(key.to_s)}: #{ActiveSupport::JSON.encode(self[key], options)}"
- end * ', '
+ result << hash.map do |key, value|
+ "#{ActiveSupport::JSON.encode(key.to_s)}:#{ActiveSupport::JSON.encode(value, options)}"
+ end * ','
result << '}'
+ end
+
+ def as_json(options = nil) #:nodoc:
+ if options
+ if attrs = options[:except]
+ except(*Array.wrap(attrs))
+ elsif attrs = options[:only]
+ slice(*Array.wrap(attrs))
+ else
+ self
+ end
+ else
+ self
+ end
end
end