Build A Simple ORM
1. Intro
Does ROR is a great framework? Yes, it does, to me, it’s lighting and very powerful. Although, the ROR project needs more RAM than most other frameworks and also difficult to scale up.
But ROR is stale, high security and has very very library supported. And the last one, ROR is the first technology I learn after I graduated from university, therefore I love Rails.
one of the reasons why many people love and use Rails today is ActiveRecord. The default ORM of Rails, more powerful and easy to use. It helps too much for us when we want to build a web app without deep experiences in SQL.
Like many developers, when I start to learn Rails, I used a few methods of ActiveRecord and don’t care what’s happening after these methods. Not bad for a beginner, but if I want to become a good developer, I need to know more details behind these methods, know deep enough to use them better.
2. Source Code
The resource of this post you can see here
3. Explaintion
The first action we need to do after read more is known what is ORM. You can read more about ORM by article.
To build a simple ORM and run a few basic methods, we need to do 2 things:
- Connect database (I use Postgresql for my example).
- Create Class using any languages that you familiar with, for me I use Ruby.
STEP 1: Create project
Create an empty project with single Gemfile with the content below:
1 | source 'https://rubygems.org' |
Install gem by command bundle install
If you get errors. let’s read more about bundler gem.
STEP 2: Connect to Database.
Create a file for the connection. I named this file is connection.rb:
1 | require 'pg' |
Note: The content above is my info login of my Database, You must change for your Database.
At this time, our project has the structure:
1 | -- simple-orm |
STEP 3: Create Main Class.
Create the main class, I named this file is mybase.rb. You can name it with any names you like, don’t matter:
1 | require_relative 'connection.rb' |
In this example above, I create two methods:
all: To return all records of this Class.
find: To find a record by ID.
STEP 4: Create Child Class Of Main Class.
In my Database, I have a table called comics. So I create a file named comics.rb to handle the comics table:
1 | require_relative 'mybase.rb' |
Finally, my project has the structure below:
1 | -- simple-orm |
Run comics.rb file with command ruby comics.rb to see what’s happening (please create your sample data first.)
References
[1]https://en.wikipedia.org/wiki/Object-relational_mapping
[2]https://medium.com/@violetmoon/understanding-orm-frameworks-with-ruby-and-activerecord-83a9e9d8490e
[3]https://stackoverflow.com/questions/2194915/what-is-orm-as-related-to-ruby-on-rails