Search code examples
rubyclassdynamic-class-creation

Class creation using eval of dynamically-created string of method def's


I have a strange situation where the code:

c = Class.new { eval parser }

... works in IRB (ruby 1.9.3) but not in code. I've tried it with and without 'class Foo' wrapping my methods. This is frustrating, to say the least. I can copy the string parser's content directly into variable parser in irb, and then create the class using the above line and my methods are all there but when I do it in code, they aren't.


Solution

  • I've solved it.

    The situation was that I was dynamically creating the definitions in order to make an optimized parser, and I was building it using incrementally added strings. As you can imagine, there was a lot of quote-escaping involved, especially with the MySQL queries. When I tested in irb, I forgot that using

    puts parser
    

    ... evaluated the string while printing, removing one level of escaping while doing so.

    The solution was simple: eval my string before class_eval'ing it.

    fetchclass = Object.const_set(
                    characteristics['shortname'],
                    Class.new { class_eval( eval parser ) } )