-
Notifications
You must be signed in to change notification settings - Fork 535
/
Copy pathresource.rb
1140 lines (925 loc) · 34.4 KB
/
resource.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'jsonapi/callbacks'
require 'jsonapi/configuration'
module JSONAPI
class Resource
include Callbacks
attr_reader :context
define_jsonapi_resources_callbacks :create,
:update,
:remove,
:save,
:create_to_many_link,
:replace_to_many_links,
:create_to_one_link,
:replace_to_one_link,
:replace_polymorphic_to_one_link,
:remove_to_many_link,
:remove_to_one_link,
:replace_fields
def initialize(model, context)
@model = model
@context = context
@reload_needed = false
@changing = false
@save_needed = false
end
def _model
@model
end
def id
_model.public_send(self.class._primary_key)
end
def identity
JSONAPI::ResourceIdentity.new(self.class, id)
end
def cache_id
[id, self.class.hash_cache_field(_model.public_send(self.class._cache_field))]
end
def is_new?
id.nil?
end
def change(callback)
completed = false
if @changing
run_callbacks callback do
completed = (yield == :completed)
end
else
run_callbacks is_new? ? :create : :update do
@changing = true
run_callbacks callback do
completed = (yield == :completed)
end
completed = (save == :completed) if @save_needed || is_new?
end
end
return completed ? :completed : :accepted
end
def remove
run_callbacks :remove do
_remove
end
end
def create_to_many_links(relationship_type, relationship_key_values, options = {})
change :create_to_many_link do
_create_to_many_links(relationship_type, relationship_key_values, options)
end
end
def replace_to_many_links(relationship_type, relationship_key_values, options = {})
change :replace_to_many_links do
_replace_to_many_links(relationship_type, relationship_key_values, options)
end
end
def replace_to_one_link(relationship_type, relationship_key_value, options = {})
change :replace_to_one_link do
_replace_to_one_link(relationship_type, relationship_key_value, options)
end
end
def replace_polymorphic_to_one_link(relationship_type, relationship_key_value, relationship_key_type, options = {})
change :replace_polymorphic_to_one_link do
_replace_polymorphic_to_one_link(relationship_type, relationship_key_value, relationship_key_type, options)
end
end
def remove_to_many_link(relationship_type, key, options = {})
change :remove_to_many_link do
_remove_to_many_link(relationship_type, key, options)
end
end
def remove_to_one_link(relationship_type, options = {})
change :remove_to_one_link do
_remove_to_one_link(relationship_type, options)
end
end
def replace_fields(field_data)
change :replace_fields do
_replace_fields(field_data)
end
end
# Override this on a resource instance to override the fetchable keys
def fetchable_fields
self.class.fields
end
def model_error_messages
_model.errors.messages
end
# Add metadata to validation error objects.
#
# Suppose `model_error_messages` returned the following error messages
# hash:
#
# {password: ["too_short", "format"]}
#
# Then to add data to the validation error `validation_error_metadata`
# could return:
#
# {
# password: {
# "too_short": {"minimum_length" => 6},
# "format": {"requirement" => "must contain letters and numbers"}
# }
# }
#
# The specified metadata is then be merged into the validation error
# object.
def validation_error_metadata
{}
end
# Override this to return resource level meta data
# must return a hash, and if the hash is empty the meta section will not be serialized with the resource
# meta keys will be not be formatted with the key formatter for the serializer by default. They can however use the
# serializer's format_key and format_value methods if desired
# the _options hash will contain the serializer and the serialization_options
def meta(_options)
{}
end
# Override this to return custom links
# must return a hash, which will be merged with the default { self: 'self-url' } links hash
# links keys will be not be formatted with the key formatter for the serializer by default.
# They can however use the serializer's format_key and format_value methods if desired
# the _options hash will contain the serializer and the serialization_options
def custom_links(_options)
{}
end
private
def save
run_callbacks :save do
_save
end
end
# Override this on a resource to return a different result code. Any
# value other than :completed will result in operations returning
# `:accepted`
#
# For example to return `:accepted` if your model does not immediately
# save resources to the database you could override `_save` as follows:
#
# ```
# def _save
# super
# return :accepted
# end
# ```
def _save(validation_context = nil)
unless @model.valid?(validation_context)
fail JSONAPI::Exceptions::ValidationErrors.new(self)
end
if defined? @model.save
saved = @model.save(validate: false)
unless saved
if @model.errors.present?
fail JSONAPI::Exceptions::ValidationErrors.new(self)
else
fail JSONAPI::Exceptions::SaveFailed.new
end
end
else
saved = true
end
@model.reload if @reload_needed
@reload_needed = false
@save_needed = !saved
:completed
end
def _remove
unless @model.destroy
fail JSONAPI::Exceptions::ValidationErrors.new(self)
end
:completed
rescue ActiveRecord::DeleteRestrictionError => e
fail JSONAPI::Exceptions::RecordLocked.new(e.message)
end
def reflect_relationship?(relationship, options)
return false if !relationship.reflect ||
(!JSONAPI.configuration.use_relationship_reflection || options[:reflected_source])
inverse_relationship = relationship.resource_klass._relationships[relationship.inverse_relationship]
if inverse_relationship.nil?
warn "Inverse relationship could not be found for #{self.class.name}.#{relationship.name}. Relationship reflection disabled."
return false
end
true
end
def _create_to_many_links(relationship_type, relationship_key_values, options)
relationship = self.class._relationships[relationship_type]
relation_name = relationship.relation_name(context: @context)
if options[:reflected_source]
@model.public_send(relation_name) << options[:reflected_source]._model
return :completed
end
# load requested related resources
# make sure they all exist (also based on context) and add them to relationship
related_resources = relationship.resource_klass.find_by_keys(relationship_key_values, context: @context)
if related_resources.count != relationship_key_values.count
# todo: obscure id so not to leak info
fail JSONAPI::Exceptions::RecordNotFound.new('unspecified')
end
reflect = reflect_relationship?(relationship, options)
related_resources.each do |related_resource|
if reflect
if related_resource.class._relationships[relationship.inverse_relationship].is_a?(JSONAPI::Relationship::ToMany)
related_resource.create_to_many_links(relationship.inverse_relationship, [id], reflected_source: self)
else
related_resource.replace_to_one_link(relationship.inverse_relationship, id, reflected_source: self)
end
@reload_needed = true
else
unless @model.public_send(relation_name).include?(related_resource._model)
@model.public_send(relation_name) << related_resource._model
end
end
end
:completed
end
def _replace_to_many_links(relationship_type, relationship_key_values, options)
relationship = self.class._relationship(relationship_type)
reflect = reflect_relationship?(relationship, options)
if reflect
existing_rids = self.class.find_related_fragments([identity], relationship_type, options)
existing = existing_rids.keys.collect {|rid| rid.id}
to_delete = existing - (relationship_key_values & existing)
to_delete.each do |key|
_remove_to_many_link(relationship_type, key, reflected_source: self)
end
to_add = relationship_key_values - (relationship_key_values & existing)
_create_to_many_links(relationship_type, to_add, {})
@reload_needed = true
else
send("#{relationship.foreign_key}=", relationship_key_values)
@save_needed = true
end
:completed
end
def _replace_to_one_link(relationship_type, relationship_key_value, _options)
relationship = self.class._relationships[relationship_type]
send("#{relationship.foreign_key}=", relationship_key_value)
@save_needed = true
:completed
end
def _replace_polymorphic_to_one_link(relationship_type, key_value, key_type, _options)
relationship = self.class._relationships[relationship_type.to_sym]
send("#{relationship.foreign_key}=", {type: key_type, id: key_value})
@save_needed = true
:completed
end
def _remove_to_many_link(relationship_type, key, options)
relationship = self.class._relationships[relationship_type]
reflect = reflect_relationship?(relationship, options)
if reflect
related_resource = relationship.resource_klass.find_by_key(key, context: @context)
if related_resource.nil?
fail JSONAPI::Exceptions::RecordNotFound.new(key)
else
if related_resource.class._relationships[relationship.inverse_relationship].is_a?(JSONAPI::Relationship::ToMany)
related_resource.remove_to_many_link(relationship.inverse_relationship, id, reflected_source: self)
else
related_resource.remove_to_one_link(relationship.inverse_relationship, reflected_source: self)
end
end
@reload_needed = true
else
@model.public_send(relationship.relation_name(context: @context)).destroy(key)
end
:completed
rescue ActiveRecord::DeleteRestrictionError => e
fail JSONAPI::Exceptions::RecordLocked.new(e.message)
rescue ActiveRecord::RecordNotFound
fail JSONAPI::Exceptions::RecordNotFound.new(key)
end
def _remove_to_one_link(relationship_type, _options)
relationship = self.class._relationships[relationship_type]
send("#{relationship.foreign_key}=", nil)
@save_needed = true
:completed
end
def _replace_fields(field_data)
field_data[:attributes].each do |attribute, value|
begin
send "#{attribute}=", value
@save_needed = true
rescue ArgumentError
# :nocov: Will be thrown if an enum value isn't allowed for an enum. Currently not tested as enums are a rails 4.1 and higher feature
raise JSONAPI::Exceptions::InvalidFieldValue.new(attribute, value)
# :nocov:
end
end
field_data[:to_one].each do |relationship_type, value|
if value.nil?
remove_to_one_link(relationship_type)
else
case value
when Hash
replace_polymorphic_to_one_link(relationship_type.to_s, value.fetch(:id), value.fetch(:type))
else
replace_to_one_link(relationship_type, value)
end
end
end if field_data[:to_one]
field_data[:to_many].each do |relationship_type, values|
replace_to_many_links(relationship_type, values)
end if field_data[:to_many]
:completed
end
class << self
def inherited(subclass)
subclass.abstract(false)
subclass.immutable(false)
subclass.caching(_caching)
subclass.paginator(_paginator)
subclass._attributes = (_attributes || {}).dup
subclass.polymorphic(false)
subclass._model_hints = (_model_hints || {}).dup
unless _model_name.empty? || _immutable
subclass.model_name(_model_name, add_model_hint: (_model_hints && !_model_hints[_model_name].nil?) == true)
end
subclass.rebuild_relationships(_relationships || {})
subclass._allowed_filters = (_allowed_filters || Set.new).dup
subclass._allowed_sort = _allowed_sort.dup
unless subclass._attributes[:id]
subclass.attribute :id, format: :id, readonly: true
end
check_reserved_resource_name(subclass._type, subclass.name)
subclass.include JSONAPI.configuration.resource_finder if JSONAPI.configuration.resource_finder
end
# A ResourceFinder is a mixin that adds functionality to find Resources and Resource Fragments
# to the core Resource class.
#
# Resource fragments are a hash with the following format:
# {
# identity: <required: a ResourceIdentity>,
# cache: <optional: the resource's cache value>
# attributes: <optional: attributes hash for attributes requested - currently unused>
# related: {
# <relationship_name>: <ResourceIdentity of a source resource in find_included_fragments>
# }
# }
#
# begin ResourceFinder Abstract methods
def find(_filters, _options = {})
# :nocov:
raise 'Abstract ResourceFinder method called. Ensure that a ResourceFinder has been set.'
# :nocov:
end
def count(_filters, _options = {})
# :nocov:
raise 'Abstract ResourceFinder method called. Ensure that a ResourceFinder has been set.'
# :nocov:
end
def find_by_keys(_keys, _options = {})
# :nocov:
raise 'Abstract ResourceFinder method called. Ensure that a ResourceFinder has been set.'
# :nocov:
end
def find_by_key(_key, _options = {})
# :nocov:
raise 'Abstract ResourceFinder method called. Ensure that a ResourceFinder has been set.'
# :nocov:
end
def find_fragments(_filters, _options = {})
# :nocov:
raise 'Abstract ResourceFinder method called. Ensure that a ResourceFinder has been set.'
# :nocov:
end
def find_included_fragments(_source_rids, _relationship_name, _options = {})
# :nocov:
raise 'Abstract ResourceFinder method called. Ensure that a ResourceFinder has been set.'
# :nocov:
end
def find_related_fragments(_source_rids, _relationship_name, _options = {})
# :nocov:
raise 'Abstract ResourceFinder method called. Ensure that a ResourceFinder has been set.'
# :nocov:
end
def count_related(_source_rid, _relationship_name, _options = {})
# :nocov:
raise 'Abstract ResourceFinder method called. Ensure that a ResourceFinder has been set.'
# :nocov:
end
#end ResourceFinder Abstract methods
def rebuild_relationships(relationships)
original_relationships = relationships.deep_dup
@_relationships = {}
if original_relationships.is_a?(Hash)
original_relationships.each_value do |relationship|
options = relationship.options.dup
options[:parent_resource] = self
options[:inverse_relationship] = relationship.inverse_relationship
_add_relationship(relationship.class, relationship.name, options)
end
end
end
def root_path_for(klass)
root_for(klass).to_s.underscore
end
def root_path_for_path(path)
JSONAPI.configuration.root_paths.detect {|p| path.start_with? p}
end
# @param [Class] klass
# @return [String]
def root_for(klass)
s = klass.to_s
JSONAPI.configuration.root_names.detect {|root| s.start_with? root.to_s}
end
# @return [String]
def root
self.class.root_for(self)
end
# @return [String]
def root_path
self.class.root_path_for(self)
end
# This is the type with its root namespace removed API::V1::Foo::Bar -> foo/bars
def _type
@_type ||= name.sub("#{self.root}::", '').sub(/Resource$/, '').underscore.pluralize.to_sym
end
# Called in two contexts
#
# 1) From within a namespace for resource resolution
#
# 2) Globally from the router context, in which case we have the fully qualified path
def resource_klass_for(type)
type = type.underscore
resource_name = _resource_name_from_type(type)
resource = resource_name.safe_constantize if resource_name
if resource.nil?
fail NameError, "JSONAPI: Could not find resource '#{type}'. (Class #{resource_name} not found)"
end
resource
end
def resource_klass_for_model(model)
resource_klass_for(resource_type_for(model))
end
def _resource_name_from_type(type)
"#{type.to_s.underscore.singularize}_resource".camelize
end
def resource_type_for(model)
model_name = model.class.to_s.underscore
if _model_hints[model_name]
_model_hints[model_name]
else
model_name.gsub("#{self.root_path}/", '')
end
end
attr_accessor :_attributes, :_relationships, :_type, :_model_hints
attr_writer :_allowed_filters, :_paginator, :_allowed_sort
def create(context)
new(create_model, context)
end
def create_model
_model_class.new
end
def routing_options(options)
@_routing_resource_options = options
end
def routing_resource_options
@_routing_resource_options ||= {}
end
# Methods used in defining a resource class
def attributes(*attrs)
options = attrs.extract_options!.dup
attrs.each do |attr|
attribute(attr, options)
end
end
def attribute(attribute_name, options = {})
attr = attribute_name.to_sym
check_reserved_attribute_name(attr)
if (attr == :id) && (options[:format].nil?)
ActiveSupport::Deprecation.warn('Id without format is no longer supported. Please remove ids from attributes, or specify a format.')
end
check_duplicate_attribute_name(attr) if options[:format].nil?
@_attributes ||= {}
@_attributes[attr] = options
define_method attr do
@model.public_send(options[:delegate] ? options[:delegate].to_sym : attr)
end unless method_defined?(attr)
define_method "#{attr}=" do |value|
@model.public_send("#{options[:delegate] ? options[:delegate].to_sym : attr}=", value)
end unless method_defined?("#{attr}=")
if options.fetch(:sortable, true) && !_has_sort?(attr)
sort attr
end
end
def attribute_to_model_field(attribute)
field_name = if attribute == :_cache_field
_cache_field
else
# Note: this will allow the returning of model attributes without a corresponding
# resource attribute, for example a belongs_to id such as `author_id` or bypassing
# the delegate.
attr = @_attributes[attribute]
attr && attr[:delegate] ? attr[:delegate].to_sym : attribute
end
if Rails::VERSION::MAJOR >= 5
attribute_type = _model_class.attribute_types[field_name.to_s]
else
attribute_type = _model_class.column_types[field_name.to_s]
end
{name: field_name, type: attribute_type}
end
def cast_to_attribute_type(value, type)
if Rails::VERSION::MAJOR >= 5
return type.cast(value)
else
return type.type_cast_from_database(value)
end
end
def default_attribute_options
{format: :default}
end
def relationship(*attrs)
options = attrs.extract_options!
klass = case options[:to]
when :one
Relationship::ToOne
when :many
Relationship::ToMany
else
#:nocov:#
fail ArgumentError.new('to: must be either :one or :many')
#:nocov:#
end
_add_relationship(klass, *attrs, options.except(:to))
end
def has_one(*attrs)
_add_relationship(Relationship::ToOne, *attrs)
end
def belongs_to(*attrs)
ActiveSupport::Deprecation.warn "In #{name} you exposed a `has_one` relationship "\
" using the `belongs_to` class method. We think `has_one`" \
" is more appropriate. If you know what you're doing," \
" and don't want to see this warning again, override the" \
" `belongs_to` class method on your resource."
_add_relationship(Relationship::ToOne, *attrs)
end
def has_many(*attrs)
_add_relationship(Relationship::ToMany, *attrs)
end
def model_name(model, options = {})
@_model_name = model.to_sym
model_hint(model: @_model_name, resource: self) unless options[:add_model_hint] == false
rebuild_relationships(_relationships)
end
def model_hint(model: _model_name, resource: _type)
resource_type = ((resource.is_a?(Class)) && (resource < JSONAPI::Resource)) ? resource._type : resource.to_s
_model_hints[model.to_s.gsub('::', '/').underscore] = resource_type.to_s
end
def filters(*attrs)
@_allowed_filters.merge!(attrs.inject({}) {|h, attr| h[attr] = {}; h})
end
def filter(attr, *args)
@_allowed_filters[attr.to_sym] = args.extract_options!
end
def sort(sorting, options = {})
self._allowed_sort[sorting.to_sym] = options
end
def sorts(*args)
options = args.extract_options!
_allowed_sort.merge!(args.inject({}) {|h, sorting| h[sorting.to_sym] = options.dup; h})
end
def primary_key(key)
@_primary_key = key.to_sym
end
def cache_field(field)
@_cache_field = field.to_sym
end
# Override in your resource to filter the updatable keys
def updatable_fields(_context = nil)
_updatable_relationships | _updatable_attributes - [:id]
end
# Override in your resource to filter the creatable keys
def creatable_fields(_context = nil)
_updatable_relationships | _updatable_attributes
end
# Override in your resource to filter the sortable keys
def sortable_fields(_context = nil)
_allowed_sort.keys
end
def sortable_field?(key, context = nil)
sortable_fields(context).include? key.to_sym
end
def fields
_relationships.keys | _attributes.keys
end
def resources_for(records, context)
records.collect do |record|
resource_for(record, context)
end
end
def resource_for(model_record, context)
resource_klass = self.resource_klass_for_model(model_record)
resource_klass.new(model_record, context)
end
def verify_filters(filters, context = nil)
verified_filters = {}
filters.each do |filter, raw_value|
verified_filter = verify_filter(filter, raw_value, context)
verified_filters[verified_filter[0]] = verified_filter[1]
end
verified_filters
end
def is_filter_relationship?(filter)
filter == _type || _relationships.include?(filter)
end
def verify_filter(filter, raw, context = nil)
filter_values = []
if raw.present?
begin
filter_values += raw.is_a?(String) ? CSV.parse_line(raw) : [raw]
rescue CSV::MalformedCSVError
filter_values << raw
end
end
strategy = _allowed_filters.fetch(filter, Hash.new)[:verify]
if strategy
values = call_method_or_proc(strategy, filter_values, context)
[filter, values]
else
if is_filter_relationship?(filter)
verify_relationship_filter(filter, filter_values, context)
else
verify_custom_filter(filter, filter_values, context)
end
end
end
def call_method_or_proc(strategy, *args)
if strategy.is_a?(Symbol) || strategy.is_a?(String)
send(strategy, *args)
else
strategy.call(*args)
end
end
def key_type(key_type)
@_resource_key_type = key_type
end
def resource_key_type
@_resource_key_type ||= JSONAPI.configuration.resource_key_type
end
def verify_key(key, context = nil)
key_type = resource_key_type
case key_type
when :integer
return if key.nil?
Integer(key)
when :string
return if key.nil?
if key.to_s.include?(',')
raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key)
else
key
end
when :uuid
return if key.nil?
if key.to_s.match(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/)
key
else
raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key)
end
else
key_type.call(key, context)
end
rescue
raise JSONAPI::Exceptions::InvalidFieldValue.new(:id, key)
end
# override to allow for key processing and checking
def verify_keys(keys, context = nil)
return keys.collect do |key|
verify_key(key, context)
end
end
# Either add a custom :verify lambda or override verify_custom_filter to allow for custom filters
def verify_custom_filter(filter, value, _context = nil)
[filter, value]
end
# Either add a custom :verify lambda or override verify_relationship_filter to allow for custom
# relationship logic, such as uuids, multiple keys or permission checks on keys
def verify_relationship_filter(filter, raw, _context = nil)
[filter, raw]
end
# quasi private class methods
def _attribute_options(attr)
default_attribute_options.merge(@_attributes[attr])
end
def _attribute_delegated_name(attr)
@_attributes.fetch(attr.to_sym, {}).fetch(:delegate, attr)
end
def _has_attribute?(attr)
@_attributes.keys.include?(attr.to_sym)
end
def _updatable_attributes
_attributes.map {|key, options| key unless options[:readonly]}.compact
end
def _updatable_relationships
@_relationships.map {|key, relationship| key unless relationship.readonly?}.compact
end
def _relationship(type)
return nil unless type
type = type.to_sym
@_relationships[type]
end
def _model_name
if _abstract
''
else
return @_model_name.to_s if defined?(@_model_name)
class_name = self.name
return '' if class_name.nil?
@_model_name = JSONAPI.configuration.root_names.inject(class_name) {|name, rn| name.sub(rn, '')}.sub(/Resource$/, '')
@_model_name.to_s
end
end
def _polymorphic_name
if !_polymorphic
''
else
@_polymorphic_name ||= _model_name.to_s.downcase
end
end
def _primary_key
@_primary_key ||= _default_primary_key
end
def _default_primary_key
@_default_primary_key ||= _model_class.respond_to?(:primary_key) ? _model_class.primary_key : :id
end
def _cache_field
@_cache_field ||= JSONAPI.configuration.default_resource_cache_field
end
def _table_name
@_table_name ||= _model_class.respond_to?(:table_name) ? _model_class.table_name : _model_name.tableize
end
def _as_parent_key
@_as_parent_key ||= "#{_type.to_s.singularize}_id"
end
def _allowed_filters
defined?(@_allowed_filters) ? @_allowed_filters : {id: {}}
end
def _allowed_sort
@_allowed_sort ||= {}
end
def _paginator
@_paginator ||= JSONAPI.configuration.default_paginator
end
def paginator(paginator)
@_paginator = paginator
end
def _polymorphic
@_polymorphic
end
def polymorphic(polymorphic = true)
@_polymorphic = polymorphic
end
def _polymorphic_types
@poly_hash ||= {}.tap do |hash|
ObjectSpace.each_object do |klass|
next unless Module === klass
if klass < ActiveRecord::Base
klass.reflect_on_all_associations(:has_many).select {|r| r.options[:as]}.each do |reflection|
(hash[reflection.options[:as]] ||= []) << klass.name.downcase
end
end
end
end
@poly_hash[_polymorphic_name.to_sym]
end
def _polymorphic_resource_klasses
@_polymorphic_resource_klasses ||= _polymorphic_types.collect do |type|
resource_klass_for(type)
end
end
def abstract(val = true)
@abstract = val
end
def _abstract
@abstract
end
def immutable(val = true)
@immutable = val
end
def _immutable
@immutable
end
def mutable?
!@immutable
end
def caching(val = true)
@caching = val
end
def _caching
@caching
end
def caching?
if @caching.nil?
!JSONAPI.configuration.resource_cache.nil? && JSONAPI.configuration.default_caching
else
@caching && !JSONAPI.configuration.resource_cache.nil?
end