The below is for added learning related to Models and Databases. None of these changes are incorporated in our final framework or app.

Use Active Record as your ORM

To use the Active Record gem for our ORM instead of Hacktive Record that we created you only need to make minor modifications.

Add and install the activerecord gem.

# Gemfile
gem 'activerecord'

bundle install

Add a database configuration file in YAML format. You can even use different databases like Postgres or MySQL since Active Record will be managing the adaptation for us.
touch config/database.yml

# config/database.yml
adapter: sqlite3
database: "db/development.sqlite3"

We don't need most of our model code, but we do need the model. And it now inherits from ActiveRecord::Base.

# app/models/article.rb
class Article < ActiveRecord::Base

  # Return title when accessing object as string, overrides default: class, encoded object id and instance variables.
  def to_s
    title
  end
end

In our boot file we need to connect to our database through Active Record.

# config/boot.rb
require 'yaml'
require 'active_record'

require_relative('routes.rb')
require_relative('../lib/jails.rb')
Dir[File.join(__dir__, '..', 'app', 'controllers', '*.rb')].each {|file| require(file) }
Dir[File.join(__dir__, '..', 'app', 'models', '*.rb')].each {|file| require(file) }

def db_configuration
  db_configuration_file = File.join(__dir__, 'database.yml')
  YAML.load(File.read(db_configuration_file))
end
 
ActiveRecord::Base.establish_connection(db_configuration)

That's all the changes needed. Restart the server and refresh the app and it should work just like before. The HacktiveRecord class still exists but isn't being used.


Modify Hacktive Record to use the config/database.yml file

To be more modular and flexible we could make the database adapter and file location and name configurable as it is in Rails. Just make the below changes.

Undo any changes you made above.

touch config/database.yml
# config/database.yml
adapter: sqlite3
database: "db/development.sqlite3"
# lib/jails/hacktive_record.rb
Change:
require "sqlite3"
module HacktiveRecord
  class Base
    DB = SQLite3::Database.new("db/development.sqlite3")
    ...
To:
require "yaml"
require "sqlite3"
module HacktiveRecord
  class Base
    # Return the database file path.
    def self.db_configuration
      db_configuration_file = File.join(__dir__, '../../config/database.yml')
      YAML.load(File.read(db_configuration_file))["database"]
    end
    DB = SQLite3::Database.new(db_configuration)
    ...