Skip to content

Cache type and attribute names as class variables #100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions lib/jsonapi-serializers/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ def serialize(object, options = {})
end

module InstanceMethods
@@class_names = {}
@@formatted_attribute_names = {}
@@unformatted_attribute_names = {}

attr_accessor :object
attr_accessor :context
attr_accessor :base_url
Expand All @@ -48,19 +52,22 @@ def id
# per the spec naming recommendations: http://jsonapi.org/recommendations/#naming
# For example, 'MyApp::LongCommment' will become the 'long-comments' type.
def type
object.class.name.demodulize.tableize.dasherize
class_name = object.class.name
@@class_names[class_name] ||= class_name.demodulize.tableize.dasherize.freeze
end

# Override this to customize how attribute names are formatted.
# By default, attribute names are dasherized per the spec naming recommendations:
# http://jsonapi.org/recommendations/#naming
def format_name(attribute_name)
attribute_name.to_s.dasherize
attr_name = attribute_name.to_s
@@formatted_attribute_names[attr_name] ||= attr_name.dasherize.freeze
end

# The opposite of format_name. Override this if you override format_name.
def unformat_name(attribute_name)
attribute_name.to_s.underscore
attr_name = attribute_name.to_s
@@unformatted_attribute_names[attr_name] ||= attr_name.underscore.freeze
end

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