From 72b6aa503afa71706ff26863350ef78d3ee69f92 Mon Sep 17 00:00:00 2001 From: Shuhei Kitagawa Date: Fri, 20 Apr 2018 20:24:48 +0900 Subject: [PATCH 1/2] Make to_json two times faster --- lib/fast_jsonapi/multi_to_json.rb | 26 ++------------------------ 1 file changed, 2 insertions(+), 24 deletions(-) diff --git a/lib/fast_jsonapi/multi_to_json.rb b/lib/fast_jsonapi/multi_to_json.rb index 108579e4..377ccabf 100644 --- a/lib/fast_jsonapi/multi_to_json.rb +++ b/lib/fast_jsonapi/multi_to_json.rb @@ -43,14 +43,9 @@ def rescue end end - def self.logger(device=nil) - return @logger = Logger.new(device) if device - @logger ||= Logger.new(IO::NULL) - end - # Encoder-compatible with default MultiJSON adapters and defaults def self.to_json_method - encode_method = String.new(%(def _fast_to_json(object)\n )) + encode_method = String.new(%(def self.to_json(object)\n )) encode_method << Result.new(LoadError) { require 'oj' %(::Oj.dump(object, mode: :compat, time_format: :ruby, use_to_json: true)) @@ -76,23 +71,6 @@ def self.to_json_method encode_method << "\nend" end - def self.to_json(object) - _fast_to_json(object) - rescue NameError - define_to_json(FastJsonapi::MultiToJson) - _fast_to_json(object) - end - - def self.define_to_json(receiver) - cl = caller_locations[0] - method_body = to_json_method - logger.debug { "Defining #{receiver}._fast_to_json as #{method_body.inspect}" } - receiver.instance_eval method_body, cl.absolute_path, cl.lineno - end - - def self.reset_to_json! - undef :_fast_to_json if method_defined?(:_fast_to_json) - logger.debug { "Undefining #{receiver}._fast_to_json" } - end + class_eval to_json_method,__FILE__, __LINE__ end end From 5f73c2db0de83a31965a38511014902917744c45 Mon Sep 17 00:00:00 2001 From: Shuhei Kitagawa Date: Fri, 20 Apr 2018 20:25:11 +0900 Subject: [PATCH 2/2] Add a test for to_json --- spec/lib/multi_to_json_spec.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 spec/lib/multi_to_json_spec.rb diff --git a/spec/lib/multi_to_json_spec.rb b/spec/lib/multi_to_json_spec.rb new file mode 100644 index 00000000..f86bd775 --- /dev/null +++ b/spec/lib/multi_to_json_spec.rb @@ -0,0 +1,11 @@ +require 'spec_helper' + +describe FastJsonapi::MultiToJson do + include_context 'movie class' + + describe 'self.to_json' do + subject { FastJsonapi::MultiToJson.to_json movie } + + it { is_expected.to eq("{\"id\":232,\"name\":\"test movie\",\"actor_ids\":[1,2,3],\"owner_id\":3,\"movie_type_id\":1}") } + end +end