|
| 1 | +# frozen_string_literal: true |
| 2 | +require 'jsonapi/deserializable' |
| 3 | + |
| 4 | +module JSONAPI |
| 5 | + module Deserializable |
| 6 | + # This does not validate a JSON API document, so errors may happen. |
| 7 | + # To truely ensure valid documents are used, it would be recommended to |
| 8 | + # use either of |
| 9 | + # - JSONAPI::Parser - for general parsing and validating |
| 10 | + # - JSONAPI::Validations - for defining validation logic. |
| 11 | + # |
| 12 | + # for 'filtereing' of fields, use ActionController::Parameters |
| 13 | + # |
| 14 | + # TODO: |
| 15 | + # - add option for type-seperator string |
| 16 | + # - add options for specifying polymorphic relationships |
| 17 | + # - this will try to be inferred based on the klass's associations |
| 18 | + # - cache deserializable_for_class |
| 19 | + # - allow custom deserializable_classes? |
| 20 | + # - then this gem would just be a very light weight wrapper around |
| 21 | + # jsonapi/deserializable |
| 22 | + class ActiveRecord |
| 23 | + require_relative 'active_record/builder' |
| 24 | + |
| 25 | + class << self |
| 26 | + def deserializable_cache |
| 27 | + @deserializable_cache ||= {} |
| 28 | + end |
| 29 | + |
| 30 | + # Creates a DeserializableResource class based off all the |
| 31 | + # attributes and relationships |
| 32 | + # |
| 33 | + # @example |
| 34 | + # JSONAPI::Deserializable::ActiveRecord[Post].new(params) |
| 35 | + def [](klass) |
| 36 | + deserializable_cache[klass.name] ||= deserializable_for(klass) |
| 37 | + end |
| 38 | + |
| 39 | + def deserializable_for(klass) |
| 40 | + JSONAPI::Deserializable::ActiveRecord::Builder.for_class(klass) |
| 41 | + end |
| 42 | + |
| 43 | + def deserializable_class(type, klass) |
| 44 | + klass || type_to_model(type) |
| 45 | + end |
| 46 | + |
| 47 | + def type_to_model(type) |
| 48 | + type.classify.safe_constantize |
| 49 | + end |
| 50 | + end |
| 51 | + |
| 52 | + # if this class is instatiated directly, i.e.: without a spceified |
| 53 | + # class via |
| 54 | + # JSONAPI::Deserializable::ActiveRecord[ExampleClass] |
| 55 | + # then when to_hash is called, the class will be derived, and |
| 56 | + # a class will be used for deserialization as if the |
| 57 | + # user specified the deserialization target class. |
| 58 | + def initialize(hash, options: {}, klass: nil) |
| 59 | + @hash = hash |
| 60 | + @options = options |
| 61 | + @klass = klass |
| 62 | + end |
| 63 | + |
| 64 | + def to_hash |
| 65 | + type = @hash['data']['type'] |
| 66 | + klass = self.class.deserializable_class(type, @klass) |
| 67 | + |
| 68 | + if klass.nil? |
| 69 | + raise "FATAL: class not found for type of `#{type}` or specified @klass `#{@klass&.name}`" |
| 70 | + end |
| 71 | + |
| 72 | + self.class[klass].call(@hash).with_indifferent_access |
| 73 | + end |
| 74 | + end |
| 75 | + end |
| 76 | +end |
0 commit comments