Skip to content

Commit fdb120c

Browse files
committed
Allow parser to handle a namespace
1 parent d419b30 commit fdb120c

File tree

4 files changed

+36
-1
lines changed

4 files changed

+36
-1
lines changed

lib/jsonapi/consumer/parsers/parser.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def handle_data(result_set, data)
8080
def choose_model_for(result_set, res)
8181
return result_set.record_class unless res['type']
8282

83-
res_type_name = res['type'].underscore.classify
83+
res_type_name = [result_set.record_class.namespace, res['type']].compact.join('/').underscore.classify
8484
(res_type_name.safe_constantize) ? res_type_name.safe_constantize : result_set.record_class
8585
end
8686

lib/jsonapi/consumer/resource.rb

+2
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ class Resource
2727
:associations,
2828
:json_key_format,
2929
:route_format,
30+
:namespace,
3031
instance_accessor: false
3132
self.primary_key = :id
3233
self.parser = Parsers::Parser
@@ -39,6 +40,7 @@ class Resource
3940
self.read_only_attributes = [:id, :type, :links, :meta, :relationships]
4041
self.requestor_class = Query::Requestor
4142
self.associations = []
43+
self.namespace = nil
4244

4345
#:underscored_key, :camelized_key, :dasherized_key, or custom
4446
self.json_key_format = :underscored_key

test/test_helper.rb

+6
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,12 @@ class UserPreference < TestResource
3535
self.primary_key = :user_id
3636
end
3737

38+
module Namespaced
39+
class Article < TestResource
40+
self.namespace = 'namespaced'
41+
end
42+
end
43+
3844
def with_altered_config(resource_class, changes)
3945
# remember and overwrite config
4046
old_config_values = {}

test/unit/parser_test.rb

+27
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,31 @@ def test_can_parse_null_data
5656
assert_nil author
5757
end
5858

59+
def test_can_find_namespaced_object
60+
stub_request(:get, "http://example.com/articles/1")
61+
.to_return(headers: {content_type: "application/vnd.api+json"}, body: {
62+
data: {
63+
type: "articles",
64+
id: "1",
65+
attributes: { title: "Rails is Omakase" },
66+
relationships: {
67+
author: {
68+
links: {
69+
related: "http://example.com/articles/1/author"
70+
}
71+
}
72+
}
73+
}
74+
}.to_json)
75+
76+
articles = Namespaced::Article.find(1)
77+
assert articles.is_a?(JSONAPI::Consumer::ResultSet)
78+
assert_equal 1, articles.length
79+
80+
article = articles.first
81+
assert_equal "1", article.id
82+
assert_equal "Rails is Omakase", article.title
83+
assert article.is_a?(Namespaced::Article)
84+
end
85+
5986
end

0 commit comments

Comments
 (0)