Sha256: ea5446bf3f9b984446f8bfecea634c7b1952aad4c836339ab5a67ddc6c8c7f2c

Contents?: true

Size: 1.62 KB

Versions: 3

Compression:

Stored size: 1.62 KB

Contents

# frozen_string_literal: true

class Serega
  module SeregaPlugins
    #
    # Plugin that checks used plugins and loads correct Preloader for selected response type
    # @see Serega::SeregaPlugins::JsonApiActiverecordPreloader
    # @see Serega::SeregaPlugins::SimpleApiActiverecordPreloader
    #
    module ActiverecordPreloads
      # @return [Symbol] plugin name
      def self.plugin_name
        :activerecord_preloads
      end

      def self.before_load_plugin(serializer_class, **opts)
        serializer_class.plugin(:preloads, **opts) unless serializer_class.plugin_used?(:preloads)
      end

      #
      # Loads plugin code and additional plugins
      #
      # @param serializer_class [Class<Serega>] Current serializer class
      # @param opts [Hash] loaded plugins opts
      #
      # @return [void]
      #
      def self.load_plugin(serializer_class, **opts)
        require_relative "./lib/preloader"

        serializer_class.include(InstanceMethods)
      end

      # Overrides Serega classes instance methods
      module InstanceMethods
        #
        # Override original #to_h method
        # @see Serega#to_h
        #
        def to_h(object, *)
          object = add_preloads(object)
          super
        end

        private

        def add_preloads(obj)
          return obj if obj.nil? || (obj.is_a?(Array) && obj.empty?)

          # preloads() method comes from :preloads plugin
          preloads = preloads()
          return obj if preloads.empty?

          Preloader.preload(obj, preloads)
        end
      end
    end

    register_plugin(ActiverecordPreloads.plugin_name, ActiverecordPreloads)
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
serega-0.4.0 lib/serega/plugins/activerecord_preloads/activerecord_preloads.rb
serega-0.3.0 lib/serega/plugins/activerecord_preloads/activerecord_preloads.rb
serega-0.2.0 lib/serega/plugins/activerecord_preloads/activerecord_preloads.rb