How to Require Active Record Working Outside of Rails

how to require active record working outside of rails

Here's how I'm using ActiveRecord outside of Rails:

#!/usr/bin/ruby

require 'active_record'
require 'mysql2' # or 'pg' or 'sqlite3'

ActiveRecord::Base.establish_connection(
adapter: 'mysql2', # or 'postgresql' or 'sqlite3'
database: 'DB_NAME',
username: 'DB_USER',
password: 'DB_PASS',
host: 'localhost'
)

# Note that the corresponding table is 'orders'
class Order < ActiveRecord::Base
end

Order.all.each do |o|
puts "o: #{o.inspect}"
end

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])

How to use ActiveRecord in a ruby script outside Rails?

require 'active_record'

# Change the following to reflect your database settings
ActiveRecord::Base.establish_connection(
adapter: 'mysql2', # or 'postgresql' or 'sqlite3' or 'oracle_enhanced'
host: 'localhost',
database: 'your_database',
username: 'your_username',
password: 'your_password'
)

# Define your classes based on the database, as always
class SomeClass < ActiveRecord::Base
#blah, blah, blah
end

# Now do stuff with it
puts SomeClass.find :all
some_class = SomeClass.new

How to access active_record database outside of rails project

You can install pry gem.

And then in your current project directory add .pryrc.

In your .pryrc you can add something like this:


current_dir = Dir.pwd
$LOAD_PATH.unshift(current_dir)

Now, every time you go to pry session just require manually your file such as:

pry(main)> require 'models/post'

This the simplest method, you can customize or extend from here.

How can I load ActiveRecord database tasks on a Ruby project outside Rails?

You could try the standalone-migrations gem:
https://github.com/thuss/standalone-migrations



Related Topics



Leave a reply



Submit