Skip to content
Advertisement

How to make generic SQL heredocs?

I’m making a mock ORM in Ruby, storing ‘forum’ data.

I have the following tables:

users (id, fname, lname), and questions (id, title, body, author_id).

a_user.create and a_question.create are more or less the same:

I’m writing another class, ModelBase, and I’d like to be able to say something like

or

. Users and Questions do not have an id until after they are added to the database.

The SQL for both of the creates basically takes all the pre-creating attributes and plops them into all columns in the corresponding table, excluding the first ‘id’ column. Is there a way to generalize the instruction “insert all the attributes of this object into the specified table for values (‘all but the first’)”?

Advertisement

Answer

We can implement a very basic ORM with some Ruby meta programming but please keep in mind that this is nothing you should use in production for security reasons. Implementing a fully working ORM is A LOT of work.

We can get the instance variables of a class with instance_variables.

Please note the @ in the beginning which we can remove with a simple gsub. We also need to reject the @id attribute. Finally with instance_variable_get we can get the actual values.

With this information we can now implement a columns and values method.

Now we need to compute the table name which we can derive from the class name of the object with self.class.name. If we put everything together it would look like this:

As mentioned in the beginning, please only use this as part of an exercise as it is not safe (SQL injections), has bugs (e.g. pluralisation of the table name and escaping of values) etc.

Another approach how this could get implemented is to query the database first which column names the table has and then derive the class attributes from it. ActiveRecord for instance does it this way.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement