# Executing ruby code stored as a string in a database

**URL:** <https://www.ruby-forum.com/t/executing-ruby-code-stored-as-a-string-in-a-database/124397>\
**Category:** Ruby\
**Created:** [December 28, 2007, 10:25am UTC](https://www.ruby-forum.com/t/executing-ruby-code-stored-as-a-string-in-a-database/124397 "2007-12-28T10:25:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![springbok](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/dfb087/32.png) [@springbok](https://www.ruby-forum.com/u/springbok)\
**Post date:** [December 28, 2007, 10:25am UTC](https://www.ruby-forum.com/t/executing-ruby-code-stored-as-a-string-in-a-database/124397/1 "2007-12-28T10:25:32Z")

</div>

I’m trying to retrieve some ruby code from a database as a string, I  
would then like to execute this code. So far I’ve tried many approaches  
but my latest uses define\_method.

I have a method defined to use define\_method, i.e.

```
def define_validation_method(name, &block)
  self.class.send(:define_method, name, &block)
end

```

What I would like to do is pass the code that I want executed to this  
method as an example:

function\_module = define\_validation\_method(  
:validate\_object)  
“do |x, y, z|  
if x \> 1  
x = y + z  
else  
x = y - z  
end  
end”

This of course does not work as the method expects a block not a string.  
Can anyone suggest how to get this method to work, or suggest another  
method. The code is being executed within a ruby class.

Thanks.

---

<div class="post-metadata">

**Author:** ![springbok](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/dfb087/32.png) [@springbok](https://www.ruby-forum.com/u/springbok)\
**Post date:** [December 28, 2007, 11:55am UTC](https://www.ruby-forum.com/t/executing-ruby-code-stored-as-a-string-in-a-database/124397/2 "2007-12-28T11:55:31Z")

</div>

Hi  
have you tried with class\_eval? when you have to execute ruby code  
contained  
in a string it should be fine for you

def define\_validation\_method(name, method\_body)  
self.class.class\_eval("

```
    def #{name}
            #{method_body}
    end

```

")  
end

Hope this helps  
Tom
