From OOP Ruby to ORM & Active Record (Part 2)

Yung L. Leung
3 min readDec 25, 2018

--

Running a program through a console works, insofar as it is not necessary to store data, permanently (From OOP Ruby to ORM & Active Record (Part 1)). As I began to create an ORM using SQLite, I realized the task was becoming tedious. SQLite enables mapping of data, regarding the objects & the relations between objects, onto a database.

I decided to simplify the task by focusing on Person, Language & their join class PL. Using an environment file, I used a line of code (SQLite3::Database.new) to make my database file (‘../DB.db’) available as a Ruby instance variable(@db). This enables me to execute SQL commands to drop tables every time I need to rebuild a database to rerun a test.

The basic functionalities of the Language class enables the creation of a table (self.create_table), save the name of a language (self.save) & list all stored languages (self.all).

Creating a table consists of storing a SQL command as a string (CREATE TABLE) and using the database (db) to execute its creation. Saving a language involves creating a language instance (language), an SQL string command (INSERT) and, once again, using the db to execute the command (sql) to insert the language (language_name) as a record. Accessing all records of languages is simply selecting all languages (SELECT *), iterating through the record list, instantiating each language & storing it as an array (languages).

The Person class can create a person table, save the person as a record, search a person by id, list all persons on record, list all languages that a person knows & have a person learn a language.

The logic behind this class is similar to the language class, but as you can see the lines of code is nearing 100.

The sole purpose of the PL class is to store the relationships between each person and their languages onto a database.

Once again, there is this repetitious process of creating instances of the class & using SQL stringed commands to store & retrieve the data.

Here I demonstrate the use of the database, Person, Language & PL classes to create their respective tables, instances & store these instances as records in the database.

Here I demonstrate the use of the instance methods of each class (Person, Language & PL) to retrieve the data from the database.

Building from simple Ruby classes that temporarily stores data of instances (From OOP Ruby to ORM & Active Record (Part 1)) to Ruby classes that persists that data SQL database is a significant advancement. Although, the use of ORM to map Ruby instances as records of a SQLite database can be a tedious task, resulting in 100s of lines of code. This brings us to Active Record, a more organized way to have your data persist.

--

--

Yung L. Leung

Developer with a passion for clean code & good UI/UX design. Inspired by the life of Jobs & Wozniak & realized through solving puzzles & building apps.