Skip to content

Commit 433bd59

Browse files
committed
Raise NoMethodError in ActiveModel::Type::Value#as_json method.
Right now since we have instance variable called `itself_if_serialize_cast_value_compatible` assigned to self when we run `as_json` we get stack too deep error because `as_json` calls `as_json` on every instance variable. And since `@itself_if_serialize_cast_value_compatible` references to `self` we run into recursion. And before that we were returning unpredictable data from `as_json` method so it's better to let it to throw an error and let user know that Value class is not supposed to be converted to json.
1 parent 2497eb0 commit 433bd59

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

activemodel/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
* Raise `NoMethodError` in `ActiveModel::Type::Value#as_json` to avoid unpredictable
2+
results.
3+
4+
*Vasiliy Ermolovich*
5+
16
* Custom attribute types that inherit from Active Model built-in types and do
27
not override the `serialize` method will now benefit from an optimization
38
when serializing attribute values for the database.

activemodel/lib/active_model/type/value.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,10 @@ def immutable_value(value) # :nodoc:
135135
value
136136
end
137137

138+
def as_json(*)
139+
raise NoMethodError
140+
end
141+
138142
private
139143
# Convenience method for types which do not need separate type casting
140144
# behavior for user and database inputs. Called by Value#cast for

activemodel/test/cases/type/value_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# frozen_string_literal: true
22

33
require "cases/helper"
4+
require "active_support/core_ext/object/json"
45

56
module ActiveModel
67
module Type
@@ -10,6 +11,12 @@ def test_type_equality
1011
assert_not_equal Type::Value.new, Type::Integer.new
1112
assert_not_equal Type::Value.new(precision: 1), Type::Value.new(precision: 2)
1213
end
14+
15+
def test_as_json_not_defined
16+
assert_raises NoMethodError do
17+
Type::Value.new.as_json
18+
end
19+
end
1320
end
1421
end
1522
end

0 commit comments

Comments
 (0)