Skip to content

Commit

Permalink
Fixing as_json method for ActiveRecord models.
Browse files Browse the repository at this point in the history
When you've got an AR Model and you override the `as_json` method,
you should be able to add default options to the renderer, like this:

    class User < ActiveRecord::Base
      def as_json(options = {})
        super(options.merge(:except => [:password_digest]))
      end
    end

This was not possible before this commit. See the added test case.
  • Loading branch information
nhocki committed Sep 30, 2011
1 parent aead572 commit c773e78
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
10 changes: 10 additions & 0 deletions activemodel/test/cases/serializers/json_serialization_test.rb
Expand Up @@ -145,4 +145,14 @@ def @contact.as_json(options); { :name => name, :created_at => created_at }; end
assert_no_match %r{"preferences":}, json assert_no_match %r{"preferences":}, json
end end


test "custom as_json options should be extendible" do
def @contact.as_json(options = {}); super(options.merge(:only => [:name])); end
json = @contact.to_json

assert_match %r{"name":"Konata Izumi"}, json
assert_no_match %r{"created_at":#{ActiveSupport::JSON.encode(Time.utc(2006, 8, 1))}}, json
assert_no_match %r{"awesome":}, json
assert_no_match %r{"preferences":}, json
end

end end
Expand Up @@ -12,7 +12,7 @@
[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass| [Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass|
klass.class_eval <<-RUBY, __FILE__, __LINE__ klass.class_eval <<-RUBY, __FILE__, __LINE__
# Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info. # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
def to_json(options = nil) def to_json(options = {})
ActiveSupport::JSON.encode(self, options) ActiveSupport::JSON.encode(self, options)
end end
RUBY RUBY
Expand Down

0 comments on commit c773e78

Please sign in to comment.