Rana. Amir
Rana. Amir

Reputation: 307

Can I load a Ruby class at runtime?

I have a very advanced question: if I have a complete class definition read from a ruby file(or loaded from a DB). can I instantiate that class and execute the methods.

example: class data stored in DB string like this.

"class Test\n\tdef hello\n\t\tputs \"Hello World\"\n\tend\n\n\tdef check (val)\n\t\tif val == \"new\"\n\t\t\tputs \"Value was 'new' \"\n\t\telse\n\t\t\tputs \"Value was not new\"\n\tend\n\nend"

Upvotes: 2

Views: 303

Answers (1)

Robert Columbia
Robert Columbia

Reputation: 6408

What you are asking about is an eval method as in Lisp or JavaScript. You are in luck, Ruby has an eval method.

To execute some basic code, just store it all in a string and then call

eval(myCodeString)

There are more ways to use eval for various circumstances. See the article I linked to for more information.

Please note that executing arbitrary strings as code is risky, as a nefarious user could inject their own Ruby code into your application a la Cross-Site Scripting (XSS) or SQL Injection.

Upvotes: 1

Related Questions