summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authortyler-ball <tyleraball@gmail.com>2014-10-06 09:33:07 -0700
committertyler-ball <tyleraball@gmail.com>2014-10-06 09:33:07 -0700
commit1a626e1958a7578455e53fe2f7cc89030b3a4092 (patch)
tree3eb9a5e9a43a137291c9cf1e85304a2e0a6be0d2
parentc5d0f4c89fa5a493fd9638d232f70088b4d0556e (diff)
downloadffi-yajl-1a626e1958a7578455e53fe2f7cc89030b3a4092.tar.gz
If an object does not have .to_json, we no longer try to call it
-rw-r--r--lib/ffi_yajl/ffi/encoder.rb6
-rw-r--r--spec/ffi_yajl/encoder_spec.rb17
2 files changed, 22 insertions, 1 deletions
diff --git a/lib/ffi_yajl/ffi/encoder.rb b/lib/ffi_yajl/ffi/encoder.rb
index 3df366c..a493158 100644
--- a/lib/ffi_yajl/ffi/encoder.rb
+++ b/lib/ffi_yajl/ffi/encoder.rb
@@ -201,7 +201,11 @@ end
# I feel dirty
class Object
def ffi_yajl(yajl_gen, state)
- json = self.to_json(state[:json_opts])
+ if self.respond_to?(:to_json)
+ json = self.to_json(state[:json_opts])
+ else
+ json = self.to_s
+ end
if ( status = FFI_Yajl.yajl_gen_number(yajl_gen, json, json.bytesize) ) != 0
FFI_Yajl::Encoder.raise_error_for_status(status)
end
diff --git a/spec/ffi_yajl/encoder_spec.rb b/spec/ffi_yajl/encoder_spec.rb
index f658d95..f89e3a1 100644
--- a/spec/ffi_yajl/encoder_spec.rb
+++ b/spec/ffi_yajl/encoder_spec.rb
@@ -87,4 +87,21 @@ describe "FFI_Yajl::Encoder" do
expect(encoder.encode(ruby)).to eq( %q{"2001-02-03T04:05:06+07:00"} )
end
+ describe "testing .to_json for Objects" do
+ class NoToJson; end
+ class HasToJson
+ def to_json(*args)
+ "{}"
+ end
+ end
+
+ it "calls .to_s for objects without .to_json" do
+ expect(encoder.encode(NoToJson.new)).to match(/#<NoToJson:\w+>/)
+ end
+
+ it "calls .to_json for objects wit .to_json" do
+ expect(encoder.encode(HasToJson.new)).to eq("{}")
+ end
+ end
+
end