Sha256: d19965df3171dcad5fec136b355ada8d9a17f77ad4a305d75f392205e9af0f47

Contents?: true

Size: 1.61 KB

Versions: 9

Compression:

Stored size: 1.61 KB

Contents

# frozen_string_literal: true

require 'active_support'

# Preload all the LHS::Records that are defined in app/models/*
# in order to collect record endpoints and to be able to identify records from hrefs
# and not only from model constant names (which is different to ActiveRecord)
module AutoloadRecords
  extend ActiveSupport::Concern

  included do
    class Engine < Rails::Engine
      initializer 'Load all LHS::Records from app/models/**' do |app|
        Middleware.require_records
        next if app.config.cache_classes

        app.config.middleware.use Middleware
      end

      class Middleware
        def initialize(app)
          @app = app
        end

        def call(env)
          self.class.require_records
          @app.call(env)
        end

        def self.model_files
          Dir.glob(Rails.root.join('app', 'models', '**', '*.rb'))
        end

        def self.require_direct_inheritance
          model_files.sort.map do |file|
            next unless File.read(file).match('LHS::Record')
            require_dependency file
            file.split('models/').last.gsub('.rb', '').classify
          end.compact
        end

        def self.require_inheriting_records(parents)
          model_files.each do |file|
            file_content = File.read(file)
            next if parents.none? { |parent| file_content.match(/\b#{parent}\b/) }
            next if file_content.match?('extend ActiveSupport::Concern')
            require_dependency file
          end
        end

        def self.require_records
          require_inheriting_records(require_direct_inheritance)
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
lhs-26.2.0 lib/lhs/concerns/autoload_records.rb
lhs-26.1.0 lib/lhs/concerns/autoload_records.rb
lhs-26.0.1 lib/lhs/concerns/autoload_records.rb
lhs-26.0.0 lib/lhs/concerns/autoload_records.rb
lhs-25.2.0 lib/lhs/concerns/autoload_records.rb
lhs-25.1.0 lib/lhs/concerns/autoload_records.rb
lhs-25.0.4 lib/lhs/concerns/autoload_records.rb
lhs-25.0.3 lib/lhs/concerns/autoload_records.rb
lhs-25.0.2 lib/lhs/concerns/autoload_records.rb