Convert string to ActiveRecord request

I have a line like "User.first" , is there any way to convert this line into an ActiveRecord request:

 User.first 

This line can be any, and I want to make it executable.

+4
source share
2 answers

From kernel # eval documentation:

eval (string [, binding [, filename [, lineno]]]) → obj click to togle Source

Computes a Ruby expression in a string. If binding is given, then it must be a Binding object, the evaluation is performed in its context. If there are optional parameters for the file name and lineno, they will be used when reporting syntax errors.

However, as @ andrew-marshall correctly points out, this is a huge security hole if you use any unapproved input. See Ruby Lock in Safe as a starting point for more information on tainted data and $ SAFE levels.

+1
source

You can try with sth, for example

 Kernel.const_get("User").send('first') 
+3
source

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


All Articles