📜 ⬆️ ⬇️

Ruby - storing a piece of code in a database

Today I found another way how to use the "trick" of interpreted languages ​​- to create and execute program code during the program operation.

You can put a piece of code into the database.

What is it for?
')
I met such a task - to write online tests.
Each test has a function — according to which the user's answers are mapped — the number of the result description

and for each test this function may be different. And I do not really want to change the program code of the site when adding each new test. I found a way out in storing this part of the code in a database in a text type field.

and now in the place where you need to calculate the test result we write:
eval (@ test.function)

function is the cell in the database table that describes the tests.
at the same time, the code is simply inserted into this place of the program and executed; it does not even have to pass the results of the user's responses as parameters;

True, if inside the line passed by eval to declare a local variable, the external program will not see it (at least I have not seen it, although everything was OK in the console), so it is better to use instance variables of the form - @varname

I suspect a fair criticism from lovers of strict PLO. But I will not give this example in agreement with the PLO, if there is a desire - experiment.

Source: https://habr.com/ru/post/66204/


All Articles