Skip to content

Commit 5e1e138

Browse files
committed
Refactor ResourceIdentifier
1 parent 4076a48 commit 5e1e138

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

lib/active_model_serializers/adapter/json_api/resource_identifier.rb

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,8 @@ module ActiveModelSerializers
22
module Adapter
33
class JsonApi
44
class ResourceIdentifier
5-
def self.type_for(class_name, serializer_type = nil, transform_options = {})
6-
if serializer_type
7-
raw_type = serializer_type
8-
else
9-
inflection =
10-
if ActiveModelSerializers.config.jsonapi_resource_type == :singular
11-
:singularize
12-
else
13-
:pluralize
14-
end
15-
16-
raw_type = class_name.underscore
17-
raw_type = ActiveSupport::Inflector.public_send(inflection, raw_type)
18-
raw_type
19-
.gsub!('/'.freeze, ActiveModelSerializers.config.jsonapi_namespace_separator)
20-
raw_type
21-
end
5+
def self.type_for(serializer, serializer_type = nil, transform_options = {})
6+
raw_type = serializer_type ? serializer_type : raw_type_from_serializer_object(serializer.object)
227
JsonApi.send(:transform_key_casing!, raw_type, transform_options)
238
end
249

@@ -30,6 +15,17 @@ def self.for_type_with_id(type, id, options)
3015
}
3116
end
3217

18+
def self.raw_type_from_serializer_object(object)
19+
class_name = object.class.name # should use model_name
20+
serializer_type = class_name.underscore
21+
singularize = ActiveModelSerializers.config.jsonapi_resource_type == :singular
22+
inflection = singularize ? :singularize : :pluralize
23+
serializer_type = ActiveSupport::Inflector.public_send(inflection, serializer_type)
24+
serializer_type
25+
.gsub!('/'.freeze, ActiveModelSerializers.config.jsonapi_namespace_separator)
26+
serializer_type
27+
end
28+
3329
# {http://jsonapi.org/format/#document-resource-identifier-objects Resource Identifier Objects}
3430
def initialize(serializer, options)
3531
@id = id_for(serializer)
@@ -48,7 +44,7 @@ def as_json
4844
private
4945

5046
def type_for(serializer, transform_options)
51-
self.class.type_for(serializer.object.class.name, serializer._type, transform_options)
47+
self.class.type_for(serializer, serializer._type, transform_options)
5248
end
5349

5450
def id_for(serializer)

0 commit comments

Comments
 (0)