How to Use Active Record Without Rails

Run ActiveRecord migrations without Rails

I managed to solve this (until Rails 6 is release at least), the implementation can be seen on textacular

task :up => :'db:connect' do
migrations = if ActiveRecord.version.version >= '5.2'
ActiveRecord::Migration.new.migration_context.migrations
else
ActiveRecord::Migrator.migrations('db/migrate')
end
ActiveRecord::Migrator.new(:up, migrations, nil).migrate
end

Not very satisfied with this solution, but this was the only way I could get the migrations to run on Rails 5, 5.1 and 5.2.

How to use rails generators without active record

You can take a look at How to create custom generators for my rails app.

Basically you will have to change the behavior of your model generators. This way you can tell which file will be created, with which code template and etc.

How to use ActiveRecord for Multiple Environment outside Rails?

What rails does may look like magic, but it's actually very simple (well, this case, at least). Here's the outline:

At startup, app loads all available database configurations. By convention, they are stored in YAML format in config/database.yml.

Then, current environment is determined. The easiest way to do this is environment variables. For example:

 MY_ENV=production ruby my_script.rb

Then, in the script, you fetch current env, pick corresponding connection configuration and use it to connect.

connection_configs = YAML.load(File.read('config/database.yml'))
current_env = ENV['MY_ENV'] || 'development' # if no value, assume development mode
ActiveRecord::Base.establish_connection(connection_configs[current_env])

ActiveRecord Schema Dump without rails

Looking at the source of the db:schema:dump task, the following code should get you started:

require 'active_record'
require 'active_record/schema_dumper'
require 'activerecord-fb-adapter'

filename = './schema.rb'

ActiveRecord::Base.establish_connection(
adapter: 'fb',
database: 'db/development.fdb',
username: 'SYSDBA',
password: 'masterkey',
host: 'localhost',
encoding: 'UTF-8',
create: true
)

File.open(filename, "w:utf-8") do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end


Related Topics



Leave a reply



Submit