lib/ecoportal/api/common/content/double_model.rb in ecoportal-api-v2-0.8.30 vs lib/ecoportal/api/common/content/double_model.rb in ecoportal-api-v2-0.8.31

- old
+ new

@@ -1,7 +1,5 @@ -require 'securerandom' - module Ecoportal module API module Common module Content # Basic model class, to **build _get_ / _set_ `methods`** for a given property @@ -10,11 +8,11 @@ class DoubleModel < Common::BaseModel NOT_USED = Common::Content::ClassHelpers::NOT_USED extend Common::Content::ClassHelpers include Common::Content::ModelHelpers - class UnlinkedModel < Exception + class UnlinkedModel < StandardError def initialize (msg = "Something went wrong when linking the document.", from: nil, key: nil) msg += " From: #{from}." if from msg += " key: #{key}." if key super(msg) end @@ -29,12 +27,12 @@ def key=(value) @key = value.to_s.freeze end - def new_uuid(length: 12) - SecureRandom.hex(length) + def new_uuid(length: 24) + uid(length) end # Same as `attr_reader` but links to a subjacent `Hash` model property # @note it does **not** create an _instance variable_ # @param methods [Array<Symbol>] the method that exposes the value @@ -206,22 +204,28 @@ dim_class.order_key = order_key end else raise "You should either specify the 'klass' of the elements or the 'enum_class'" end - embed(method, key: key, multiple: true, klass: eclass) + embed(method, key: key, multiple: true, klass: eclass) do |instance_with_called_method| + # keep reference to the original class to resolve the `klass` dependency + # See stackoverflow: https://stackoverflow.com/a/73709529/4352306 + referrer_class = instance_with_called_method.class + eclass.klass = {referrer_class => klass} if klass + end end private - def embed(method, key: method, nullable: false, multiple: false, klass:) + def embed(method, key: method, nullable: false, multiple: false, klass:, &block) method = method.to_s.freeze var = instance_variable_name(method).freeze k = key.to_s.freeze # retrieving method (getter) define_method(method) do + yield(self) if block_given? return instance_variable_get(var) if instance_variable_defined?(var) unless nullable doc[k] ||= multiple ? [] : {} end return variable_set(var, nil) unless doc[k] @@ -237,10 +241,10 @@ @forced_model_keys ||= {} end end - inheritable_class_vars :forced_model_keys + inheritable_class_vars :forced_model_keys, :key attr_reader :_parent, :_key def initialize(doc = {}, parent: self, key: nil) @_dim_vars = []