File tree Expand file tree Collapse file tree 2 files changed +13
-7
lines changed Expand file tree Collapse file tree 2 files changed +13
-7
lines changed Original file line number Diff line number Diff line change @@ -25,12 +25,16 @@ class RubyObjectEncoder {
25
25
switch (rb_type (key)) {
26
26
case T_SYMBOL:
27
27
key = rb_sym2str (key);
28
- /* FALLTHRU */
28
+ /* FALLTHRU */
29
29
case T_STRING:
30
30
writer.Key (RSTRING_PTR (key), RSTRING_LEN (key), false );
31
31
return ;
32
32
default :
33
- raise_unknown (key);
33
+ {
34
+ VALUE str = rb_funcall (key, id_to_s, 0 );
35
+ Check_Type (str, T_STRING);
36
+ encode_string (str);
37
+ }
34
38
}
35
39
}
36
40
@@ -133,11 +137,6 @@ class RubyObjectEncoder {
133
137
}
134
138
}
135
139
136
- void raise_unknown (VALUE obj) {
137
- VALUE inspect = rb_inspect (obj);
138
- rb_raise (rb_eEncodeError, " can't encode type: %s" , StringValueCStr (inspect));
139
- }
140
-
141
140
public:
142
141
RubyObjectEncoder (): buf(), writer(buf), depth(0 ) {
143
142
};
Original file line number Diff line number Diff line change @@ -59,6 +59,13 @@ def test_encode_hash
59
59
assert_equal '{"foo":"bar"}' , encode ( { "foo" => "bar" } )
60
60
end
61
61
62
+ def test_encode_hash_nonstring_keys
63
+ assert_equal '{"1":2}' , encode ( { 1 => 2 } )
64
+ assert_equal '{"{1=>2}":3}' , encode ( { { 1 => 2 } => 3 } )
65
+ assert_equal '{"[\\"foo\\"]":"bar"}' , encode ( { [ "foo" ] => "bar" } )
66
+ assert_match ( /{"#<Object:0x[0-9a-f]+>":2}/ , encode ( { Object . new => 2 } ) )
67
+ end
68
+
62
69
def test_encode_string
63
70
assert_equal '""' , encode ( "" )
64
71
assert_equal '"1"' , encode ( "1" )
You can’t perform that action at this time.
0 commit comments