|
| 1 | +# This file is responsible for one-time set up of ActiveRecord |
| 2 | +# 1 - Set ActiveRecord connection & options |
| 3 | +# 2 - Delete existing database |
| 4 | +# 3 - Expose "TestModels::ActiveRecord.initialize_model" to allow dynamically creating models |
| 5 | +require 'active_record' |
| 6 | + |
| 7 | +ActiveRecord::Base.logger = Logger.new($stdout) |
| 8 | +ActiveRecord::Base.logger.level = Logger::WARN |
| 9 | +ActiveRecord::Base.establish_connection( |
| 10 | + 'adapter' => defined?(JRUBY_VERSION) ? 'jdbcsqlite3' : 'sqlite3', |
| 11 | + 'database' => 'data.sqlite3', |
| 12 | + 'pool' => 5, |
| 13 | + 'timeout' => 5000 |
| 14 | +) |
| 15 | + |
| 16 | +ActiveRecord::Base.raise_in_transactional_callbacks = true if ActiveRecord::Base.respond_to?(:raise_in_transactional_callbacks) |
| 17 | + |
| 18 | +FileUtils.rm_f('data.sqlite3') |
| 19 | + |
| 20 | +module Models |
| 21 | + module ActiveRecord |
| 22 | + def self.schema |
| 23 | + @schema ||= ::ActiveRecord::Schema.new.tap { |schema| schema.verbose = false } |
| 24 | + end |
| 25 | + |
| 26 | + def self.initialize_model(specification) |
| 27 | + schema.create_table specification.name.underscore.pluralize do |t| |
| 28 | + specification.fields.each do |field| |
| 29 | + t.send(field.type, field.name) |
| 30 | + end |
| 31 | + end |
| 32 | + |
| 33 | + klass = Class.new(::ActiveRecord::Base) do |
| 34 | + define_singleton_method(:model_name) do |
| 35 | + name = "Models::ActiveRecord::#{specification.name}" |
| 36 | + ActiveModel::Name.new(self, nil, name) |
| 37 | + end |
| 38 | + end |
| 39 | + |
| 40 | + const_set(specification.name, klass) |
| 41 | + |
| 42 | + klass.class_eval(&specification.body) |
| 43 | + end |
| 44 | + end |
| 45 | +end |
0 commit comments