DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Metaprogramming New Classes In Ruby

  • submit to reddit
        Take a class name in a string ('Test' or 'My::Module::Test') and create a new class for it.

old method.  didn't like evaling the string though...
agent_name = "#{model_name.to_s.camelize}Agent"
agent_class = instance_eval %{Object::#{agent_name} =}

new method
agent_name_pieces = agent_name.split('::')
agent_class_name = agent_name_pieces.pop
agent_module = agent_name_pieces.inject(Object) { |obj, name| obj.const_defined?(name) ? obj.const_get(name) : obj.const_set(name,  }
agent_class = agent_module.const_set(agent_class_name,

For acedemic purposes mainly, I don't know if the new method is any faster.  I just wanted a version with as little string evaluation as possible.  See my <a href="">blog entry</a> on this very topic.