Skip to content

Instantly share code, notes, and snippets.

@thorncp
Last active March 23, 2020 23:28
Show Gist options
  • Save thorncp/331964892f1379f28758f05e5987201f to your computer and use it in GitHub Desktop.
Save thorncp/331964892f1379f28758f05e5987201f to your computer and use it in GitHub Desktop.
ActiveRecord without Rails (the models live in a Rails app)

ActiveRecord without Rails

I wanted to load models from a Rails app in a background worker. First attempt was to require_relative "../config/environment", which brings in the whole app. This works fine, but is quite slow.

I get easily annoyed and frustrated with slow software, so I wanted to find a way to load the models I needed, without pulling in the whole app. The approach here is where I landed.

require "active_record"
require "erb"
require "yaml"
unless ActiveRecord::Base.connected?
env = ENV.fetch("RAILS_ENV", "development")
raw_config = ERB.new(File.read("config/database.yml")).result
db_config = YAML.load(raw_config).fetch(env)
ActiveRecord::Base.establish_connection(db_config)
end
require_relative "../app/models/application_record"
# require the models you need and use them
@mculp
Copy link

mculp commented Mar 23, 2020

🤩

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment