Sha256: 70730aa49802748f4c8ac70589866b36120d1d218d4ded1910ee293bc074cdda

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

require 'active_record'

module Temping
  def self.included(base)
    unless ActiveRecord::Base.connected?
      ActiveRecord::Base.configurations['temping'] = { 
        :adapter  => 'sqlite3', :database => ':memory:'
      }    
      ActiveRecord::Base.establish_connection 'temping' 
    end
  end
  
  def create_model(model_name, &block)    
    model_class = model_name.to_s.classify
    unless eval("defined?(#{model_class})")
      factory = ModelFactory.new(model_class, &block)
      factory.klass
    end
  end

  class ModelFactory
    attr_accessor :klass
    
    def initialize(model_class, &block)
      @klass = Class.new(ActiveRecord::Base)
      Object.const_set(model_class, @klass)
      create_table
      add_methods
      @klass.class_eval(&block) if block_given?
    end

    private

      def create_table
        @klass.connection.create_table(@klass.table_name, :temporary => true) do |table| 
          table.integer :id
        end
      end

      def add_methods
        class << @klass
          def with_columns
            connection.change_table(table_name) { |table| yield(table) }
          end

          def table_exists?
            true
          end
        end
      end
    
  end   
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
temping-1.3.0 lib/temping.rb