Sha256: 7940362cd6ee339f35fab0b1c9714745aa7c1aff7e8214c3b207d700259efa9e

Contents?: true

Size: 1.32 KB

Versions: 4

Compression:

Stored size: 1.32 KB

Contents

class Temping::ModelFactory
  DEFAULT_OPTIONS = {temporary: true}

  def initialize(name, namespace, options = {}, &block)
    @name = name
    @namespace = namespace
    @options = options
    klass.class_eval(&block) if block
    klass.reset_column_information
  end

  def klass
    @klass ||= @namespace.const_get(@name)
  rescue NameError
    @klass = build
  end

  private

  def build
    Class.new(parent_class_name).tap do |klass|
      @namespace.const_set(@name, klass)
      klass.primary_key = @options[:primary_key] || :id
      create_table(@options.except(:parent_class))
      add_methods
      klass.namespace = @namespace
    end
  end

  def parent_class_name
    @options.fetch(:parent_class, default_parent_class_name)
  end

  def default_parent_class_name
    if defined?(ApplicationRecord)
      ApplicationRecord
    else
      ActiveRecord::Base
    end
  end

  def create_table(options = {})
    connection.create_table(table_name, **DEFAULT_OPTIONS.merge(options))
  end

  def add_methods
    class << klass
      attr_accessor :namespace

      def with_columns
        connection.change_table(table_name) do |table|
          yield(table)
        end
      end

      def table_exists?
        true
      end
    end
  end

  def connection
    klass.connection
  end

  def table_name
    klass.table_name
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
temping-4.3.0 lib/temping/model_factory.rb
temping-4.2.0 lib/temping/model_factory.rb
temping-4.1.1 lib/temping/model_factory.rb
temping-4.1.0 lib/temping/model_factory.rb