Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #9751: to_json_accepts_options.2.diff

File to_json_accepts_options.2.diff, 10.3 kB (added by chuyeow, 9 months ago)

Change to_json method to accept options for JSON-encodable types (using hash keys instead of Hash# slice and Hash#except)

  • activesupport/test/json/encoding_test.rb

    old new  
    6969    assert_equal %w( "$" "A" "A0" "A0B" "_" "a" 0 1 ), object_keys(values.to_json) 
    7070  end 
    7171 
     72  def test_hash_should_allow_key_filtering_with_only 
     73    assert_equal %({"a": 1}), { 'a' => 1, :b => 2, :c => 3 }.to_json(:only => 'a') 
     74  end 
     75 
     76  def test_hash_should_allow_key_filtering_with_except 
     77    assert_equal %({"b": 2}), { 'foo' => 'bar', :b => 2, :c => 3 }.to_json(:except => ['foo', :c]) 
     78  end 
     79 
    7280  protected 
    7381    def object_keys(json_object) 
    7482      json_object[1..-2].scan(/([^{}:,\s]+):/).flatten.sort 
    7583    end 
    7684end 
     85 
     86uses_mocha 'JsonOptionsTests' do 
     87   
     88  class JsonOptionsTests < Test::Unit::TestCase 
     89    def test_enumerable_should_passthrough_options_to_elements 
     90      json_options = { :include => :posts } 
     91      ActiveSupport::JSON.expects(:encode).with(1, json_options) 
     92      ActiveSupport::JSON.expects(:encode).with(2, json_options) 
     93      ActiveSupport::JSON.expects(:encode).with('foo', json_options) 
     94 
     95      [1, 2, 'foo'].to_json(json_options) 
     96    end 
     97  end 
     98end 
  • activesupport/lib/active_support/json/encoders/date.rb

    old new  
    11class Date 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
    33    %("#{strftime("%m/%d/%Y")}") 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoders/time.rb

    old new  
    11class Time 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
    33    %("#{strftime("%m/%d/%Y %H:%M:%S %Z")}") 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoders/enumerable.rb

    old new  
    11module Enumerable 
    2   def to_json #:nodoc: 
    3     "[#{map { |value| ActiveSupport::JSON.encode(value) } * ', '}]" 
     2  def to_json(options = {}) #:nodoc: 
     3    "[#{map { |value| ActiveSupport::JSON.encode(value, options) } * ', '}]" 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoders/false_class.rb

    old new  
    11class FalseClass 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
    33    'false' 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoders/numeric.rb

    old new  
    11class Numeric 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
    33    to_s 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoders/hash.rb

    old new  
    11class Hash 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
     3    hash_keys = self.keys 
     4 
     5    if options[:except] 
     6      hash_keys = hash_keys - Array(options[:except]) 
     7    elsif options[:only] 
     8      hash_keys = hash_keys & Array(options[:only]) 
     9    end 
     10 
    311    returning result = '{' do 
    4       result << map do |key, value
    5         "#{ActiveSupport::JSON.encode(key)}: #{ActiveSupport::JSON.encode(value)}" 
     12      result << hash_keys.map do |key
     13        "#{ActiveSupport::JSON.encode(key)}: #{ActiveSupport::JSON.encode(self[key], options)}" 
    614      end * ', ' 
    715      result << '}' 
    816    end 
  • activesupport/lib/active_support/json/encoders/true_class.rb

    old new  
    11class TrueClass 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
    33    'true' 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoders/symbol.rb

    old new  
    11class Symbol 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
    33    ActiveSupport::JSON.encode(to_s) 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoders/object.rb

    old new  
    11class Object 
    22  # Dumps object in JSON (JavaScript Object Notation).  See www.json.org for more info. 
    3   # 
    4   #   Account.find(1).to_json 
    5   #   => "{attributes: {username: \"foo\", id: \"1\", password: \"bar\"}}" 
    6   # 
    7   def to_json 
    8     ActiveSupport::JSON.encode(instance_values) 
     3  def to_json(options = {}) 
     4    ActiveSupport::JSON.encode(instance_values, options) 
    95  end 
    106end 
  • activesupport/lib/active_support/json/encoders/string.rb

    old new  
    1717end 
    1818 
    1919class String 
    20   def to_json #:nodoc: 
     20  def to_json(options = {}) #:nodoc: 
    2121    '"' + gsub(/[\010\f\n\r\t"\\><]/) { |s| 
    2222      ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s] 
    2323    }.gsub(/([\xC0-\xDF][\x80-\xBF]| 
  • activesupport/lib/active_support/json/encoders/nil_class.rb

    old new  
    11class NilClass 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
    33    'null' 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoders/regexp.rb

    old new  
    11class Regexp 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
    33    inspect 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoders/date_time.rb

    old new  
    11class DateTime 
    2   def to_json #:nodoc: 
     2  def to_json(options = {}) #:nodoc: 
    33    %("#{strftime("%m/%d/%Y %H:%M:%S %Z")}") 
    44  end 
    55end 
  • activesupport/lib/active_support/json/encoding.rb

    old new  
    1717      REFERENCE_STACK_VARIABLE = :json_reference_stack #:nodoc: 
    1818 
    1919      # Converts a Ruby object into a JSON string. 
    20       def encode(value
     20      def encode(value, options = {}
    2121        raise_on_circular_reference(value) do 
    22           value.send(:to_json
     22          value.send(:to_json, options
    2323        end 
    2424      end 
    2525 
  • activerecord/test/json_serialization_test.rb

    old new  
    6868 
    6969  def setup 
    7070    @david = authors(:david) 
     71    @mary = authors(:mary) 
    7172  end 
    7273 
    7374  def test_includes_uses_association_name 
    7475    json = @david.to_json(:include => :posts) 
    75      
     76 
    7677    assert_match %r{"posts": \[}, json 
    7778 
    7879    assert_match %r{"id": 1}, json 
     
    140141    assert_match %r{"favorite_quote": "Constraints are liberating"}, json 
    141142    assert_equal %r{"favorite_quote": }.match(json).size, 1 
    142143  end 
     144 
     145  def test_should_allow_only_option_for_list_of_authors 
     146    authors = [@david, @mary] 
     147 
     148    assert_equal %([{"name": "David"}, {"name": "Mary"}]), authors.to_json(:only => :name) 
     149  end 
     150 
     151  def test_should_allow_except_option_for_list_of_authors 
     152    authors = [@david, @mary] 
     153 
     154    assert_equal %([{"id": 1}, {"id": 2}]), authors.to_json(:except => [:name, :author_address_id]) 
     155  end 
     156 
     157  def test_should_allow_includes_for_list_of_authors 
     158    authors = [@david, @mary] 
     159    json = authors.to_json( 
     160      :only => :name, 
     161      :include => { 
     162        :posts => { :only => :id } 
     163      } 
     164    ) 
     165 
     166    assert_equal %([{"name": "David", "posts": [{"id": 1}, {"id": 2}, {"id": 4}, {"id": 5}, {"id": 6}]}, {"name": "Mary", "posts": [{"id": 7}]}]), json 
     167  end 
     168 
     169  def test_should_allow_options_for_hash_of_authors 
     170    authors_hash = { 
     171      1 => @david, 
     172      2 => @mary 
     173    } 
     174 
     175    assert_equal %({1: {"name": "David"}}), authors_hash.to_json(:only => [1, :name]) 
     176  end 
    143177end 
  • activerecord/lib/active_record/serializers/json_serializer.rb

    old new  
    11module ActiveRecord #:nodoc: 
    22  module Serialization 
    3     def to_json(options = {}, &block
     3    def to_json(options = {}
    44      JsonSerializer.new(self, options).to_s 
    55    end 
    66