Sha256: c03e031411d57273d18931667490a1f4dd9329b9c88a8a5b957a36b494d03832

Contents?: true

Size: 1.69 KB

Versions: 1

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

require 'active_record'
require 'active_support/core_ext/string/inflections'
require 'English'
require 'with_model/constant_stubber'
require 'with_model/methods'
require 'with_model/table'

module WithModel
  class Model
    attr_writer :model_block, :table_block, :table_options

    def initialize(name, superclass: ActiveRecord::Base)
      @name = name.to_sym
      @model_block = nil
      @table_block = nil
      @table_options = {}
      @superclass = superclass
    end

    def create
      table.create
      @model = Class.new(@superclass) do
        extend WithModel::Methods
      end
      stubber.stub_const @model
      setup_model
    end

    def destroy
      stubber.unstub_const
      remove_from_superclass_descendants
      reset_dependencies_cache
      table.destroy
      @model = nil
    end

    private

    def const_name
      @name.to_s.camelize.to_sym
    end

    def setup_model
      @model.table_name = table_name
      @model.class_eval(&@model_block) if @model_block
      @model.reset_column_information
    end

    def remove_from_superclass_descendants
      return unless @model.superclass.respond_to?(:direct_descendants)
      @model.superclass.direct_descendants.delete(@model)
    end

    def reset_dependencies_cache
      return unless defined?(ActiveSupport::Dependencies::Reference)
      ActiveSupport::Dependencies::Reference.clear!
    end

    def stubber
      @stubber ||= ConstantStubber.new const_name
    end

    def table
      @table ||= Table.new table_name, @table_options, &@table_block
    end

    def table_name
      uid = "#{$PID}_#{Thread.current.object_id}"
      "with_model_#{@name.to_s.tableize}_#{uid}"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
with_model-2.1.0 lib/with_model/model.rb