Skip to content

Commit 5dfc662

Browse files
timhainesfotinakis
authored andcommitted
Cache type and attribute names as class variables (#100)
* Cache class and attribute names * Freeze cache values.
1 parent e248903 commit 5dfc662

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

lib/jsonapi-serializers/serializer.rb

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,10 @@ def serialize(object, options = {})
2222
end
2323

2424
module InstanceMethods
25+
@@class_names = {}
26+
@@formatted_attribute_names = {}
27+
@@unformatted_attribute_names = {}
28+
2529
attr_accessor :object
2630
attr_accessor :context
2731
attr_accessor :base_url
@@ -48,19 +52,22 @@ def id
4852
# per the spec naming recommendations: http://jsonapi.org/recommendations/#naming
4953
# For example, 'MyApp::LongCommment' will become the 'long-comments' type.
5054
def type
51-
object.class.name.demodulize.tableize.dasherize
55+
class_name = object.class.name
56+
@@class_names[class_name] ||= class_name.demodulize.tableize.dasherize.freeze
5257
end
5358

5459
# Override this to customize how attribute names are formatted.
5560
# By default, attribute names are dasherized per the spec naming recommendations:
5661
# http://jsonapi.org/recommendations/#naming
5762
def format_name(attribute_name)
58-
attribute_name.to_s.dasherize
63+
attr_name = attribute_name.to_s
64+
@@formatted_attribute_names[attr_name] ||= attr_name.dasherize.freeze
5965
end
6066

6167
# The opposite of format_name. Override this if you override format_name.
6268
def unformat_name(attribute_name)
63-
attribute_name.to_s.underscore
69+
attr_name = attribute_name.to_s
70+
@@unformatted_attribute_names[attr_name] ||= attr_name.underscore.freeze
6471
end
6572

6673
# Override this to provide resource-object jsonapi object containing the version in use.

0 commit comments

Comments
 (0)