Skip to content

Commit 1a88047

Browse files
author
Lee Richmond
committed
Raise helpful error if missing serializer
1 parent 3095691 commit 1a88047

File tree

3 files changed

+44
-6
lines changed

3 files changed

+44
-6
lines changed

lib/jsonapi_compliable/errors.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,23 @@ module Errors
33
class BadFilter < StandardError; end
44
class ValidationError < StandardError; end
55

6+
class MissingSerializer < StandardError
7+
def initialize(class_name, serializer_name)
8+
@class_name = class_name
9+
@serializer_name = serializer_name
10+
end
11+
12+
def message
13+
<<-MSG
14+
Could not find serializer for class '#{@class_name}'!
15+
16+
Looked for '#{@serializer_name}' but doesn't appear to exist.
17+
18+
Use a custom Inferrer if you'd like different lookup logic.
19+
MSG
20+
end
21+
end
22+
623
class UnsupportedPageSize < StandardError
724
def initialize(size, max)
825
@size, @max = size, max

lib/jsonapi_compliable/util/render_options.rb

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,6 @@ class RenderOptions
66
def self.generate(object, query_hash, overrides = {})
77
resolved = object.respond_to?(:resolve) ? object.resolve : object
88

9-
inferrer = ::Hash.new do |h, k|
10-
names = k.to_s.split('::')
11-
klass = names.pop
12-
h[k] = [*names, "Serializable#{klass}"].join('::').safe_constantize
13-
end
14-
159
fields = query_hash[:fields].dup
1610
extra_fields = query_hash[:extra_fields]
1711

@@ -37,6 +31,21 @@ def self.generate(object, query_hash, overrides = {})
3731

3832
options
3933
end
34+
35+
def self.inferrer
36+
::Hash.new do |h, k|
37+
names = k.to_s.split('::')
38+
klass = names.pop
39+
serializer_name = [*names, "Serializable#{klass}"].join('::')
40+
serializer = serializer_name.safe_constantize
41+
if serializer
42+
h[k] = serializer
43+
else
44+
raise Errors::MissingSerializer.new(k, serializer_name)
45+
end
46+
end
47+
end
48+
private_class_method :inferrer
4049
end
4150
end
4251
end

spec/integration/rails/finders_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,18 @@ def json
235235
end
236236
end
237237

238+
context 'when no serializer is found' do
239+
before do
240+
allow_any_instance_of(String).to receive(:safe_constantize) { nil }
241+
end
242+
243+
it 'raises helpful error' do
244+
expect {
245+
get :index
246+
}.to raise_error(JsonapiCompliable::Errors::MissingSerializer)
247+
end
248+
end
249+
238250
context 'sideloading has_many' do
239251
# TODO: may want to blow up here, only for index action
240252
it 'allows pagination of sideloaded resource' do

0 commit comments

Comments
 (0)