11require 'jsonapi/formatter'
22require 'jsonapi/operations_processor'
33require 'jsonapi/active_record_operations_processor'
4+ require 'concurrent'
45
56module JSONAPI
67 class Configuration
78 attr_reader :json_key_format ,
89 :resource_key_type ,
9- :key_formatter ,
1010 :route_format ,
11- :route_formatter ,
1211 :raise_if_parameters_not_allowed ,
1312 :operations_processor ,
1413 :allow_include ,
@@ -23,7 +22,8 @@ class Configuration
2322 :top_level_meta_record_count_key ,
2423 :exception_class_whitelist ,
2524 :always_include_to_one_linkage_data ,
26- :always_include_to_many_linkage_data
25+ :always_include_to_many_linkage_data ,
26+ :cache_formatters
2727
2828 def initialize
2929 #:underscored_key, :camelized_key, :dasherized_key, or custom
@@ -74,20 +74,69 @@ def initialize
7474 # NOTE: always_include_to_many_linkage_data is not currently implemented
7575 self . always_include_to_one_linkage_data = false
7676 self . always_include_to_many_linkage_data = false
77+
78+ # Formatter Caching
79+ # Set to false to disable caching of string operations on keys and links.
80+ self . cache_formatters = true
81+ end
82+
83+ def cache_formatters = ( bool )
84+ @cache_formatters = bool
85+ if bool
86+ @key_formatter_tlv = Concurrent ::ThreadLocalVar . new
87+ @route_formatter_tlv = Concurrent ::ThreadLocalVar . new
88+ else
89+ @key_formatter_tlv = nil
90+ @route_formatter_tlv = nil
91+ end
7792 end
7893
7994 def json_key_format = ( format )
8095 @json_key_format = format
81- @key_formatter = JSONAPI ::Formatter . formatter_for ( format )
96+ if @cache_formatters
97+ @key_formatter_tlv = Concurrent ::ThreadLocalVar . new
98+ end
99+ end
100+
101+ def route_format = ( format )
102+ @route_format = format
103+ if @cache_formatters
104+ @route_formatter_tlv = Concurrent ::ThreadLocalVar . new
105+ end
106+ end
107+
108+ def key_formatter
109+ if self . cache_formatters
110+ formatter = @key_formatter_tlv . value
111+ return formatter if formatter
112+ end
113+
114+ formatter = JSONAPI ::Formatter . formatter_for ( self . json_key_format )
115+
116+ if self . cache_formatters
117+ formatter = @key_formatter_tlv . value = formatter . cached
118+ end
119+
120+ return formatter
82121 end
83122
84123 def resource_key_type = ( key_type )
85124 @resource_key_type = key_type
86125 end
87126
88- def route_format = ( format )
89- @route_format = format
90- @route_formatter = JSONAPI ::Formatter . formatter_for ( format )
127+ def route_formatter
128+ if self . cache_formatters
129+ formatter = @route_formatter_tlv . value
130+ return formatter if formatter
131+ end
132+
133+ formatter = JSONAPI ::Formatter . formatter_for ( self . route_format )
134+
135+ if self . cache_formatters
136+ formatter = @route_formatter_tlv . value = formatter . cached
137+ end
138+
139+ return formatter
91140 end
92141
93142 def operations_processor = ( operations_processor )
0 commit comments