summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authortyler-ball <tyleraball@gmail.com>2014-10-07 10:54:54 -0700
committertyler-ball <tyleraball@gmail.com>2014-10-07 10:54:54 -0700
commit31df485a023364383353dabb97f9f0609ceddde6 (patch)
treed2b7bb7e620640c02c2ac27a7b634c2b3c8d30af
parent3af1ec06bd861bf0eb01863cbe02dffadbf45503 (diff)
downloadffi-yajl-31df485a023364383353dabb97f9f0609ceddde6.tar.gz
Making necessary C changes to only call to_json if it is present
-rw-r--r--ext/ffi_yajl/ext/encoder/encoder.c20
-rw-r--r--lib/ffi_yajl/ffi/encoder.rb2
-rw-r--r--spec/ffi_yajl/encoder_spec.rb2
3 files changed, 15 insertions, 9 deletions
diff --git a/ext/ffi_yajl/ext/encoder/encoder.c b/ext/ffi_yajl/ext/encoder/encoder.c
index 0c917cb..90b125b 100644
--- a/ext/ffi_yajl/ext/encoder/encoder.c
+++ b/ext/ffi_yajl/ext/encoder/encoder.c
@@ -272,14 +272,20 @@ static VALUE rb_cObject_ffi_yajl(VALUE self, VALUE rb_yajl_gen, VALUE state) {
yajl_gen_status status;
ID sym_to_json = rb_intern("to_json");
VALUE str;
- VALUE json_opts = rb_hash_aref(state, rb_str_new2("json_opts"));
- struct yajl_gen_t *yajl_gen;
- Data_Get_Struct(rb_yajl_gen, struct yajl_gen_t, yajl_gen);
- str = rb_funcall(self, sym_to_json, 1, json_opts);
- CHECK_STATUS(
- yajl_gen_number(yajl_gen, (char *)RSTRING_PTR(str), RSTRING_LEN(str))
- );
+ if ( rb_respond_to(self, sym_to_json) ) {
+ VALUE json_opts = rb_hash_aref(state, rb_str_new2("json_opts"));
+ struct yajl_gen_t *yajl_gen;
+ Data_Get_Struct(rb_yajl_gen, struct yajl_gen_t, yajl_gen);
+
+ str = rb_funcall(self, sym_to_json, 1, json_opts);
+ CHECK_STATUS(
+ yajl_gen_number(yajl_gen, (char *)RSTRING_PTR(str), RSTRING_LEN(str))
+ );
+ } else {
+ object_to_s_ffi_yajl(self, rb_yajl_gen, state);
+ }
+
return Qnil;
}
diff --git a/lib/ffi_yajl/ffi/encoder.rb b/lib/ffi_yajl/ffi/encoder.rb
index a493158..3724e49 100644
--- a/lib/ffi_yajl/ffi/encoder.rb
+++ b/lib/ffi_yajl/ffi/encoder.rb
@@ -204,7 +204,7 @@ class Object
if self.respond_to?(:to_json)
json = self.to_json(state[:json_opts])
else
- json = self.to_s
+ json = "\"#{to_s}\""
end
if ( status = FFI_Yajl.yajl_gen_number(yajl_gen, json, json.bytesize) ) != 0
FFI_Yajl::Encoder.raise_error_for_status(status)
diff --git a/spec/ffi_yajl/encoder_spec.rb b/spec/ffi_yajl/encoder_spec.rb
index f89e3a1..02bc020 100644
--- a/spec/ffi_yajl/encoder_spec.rb
+++ b/spec/ffi_yajl/encoder_spec.rb
@@ -96,7 +96,7 @@ describe "FFI_Yajl::Encoder" do
end
it "calls .to_s for objects without .to_json" do
- expect(encoder.encode(NoToJson.new)).to match(/#<NoToJson:\w+>/)
+ expect(encoder.encode(NoToJson.new)).to match(/^"#<NoToJson:\w+>"$/)
end
it "calls .to_json for objects wit .to_json" do