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

09.06.2005
| 2161 views |
  • 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} = Class.new(Administration::Agent)}

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, Module.new)  }
agent_class = agent_module.const_set(agent_class_name, Class.new(Administration::Agent))

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="http://techno-weenie.net/blog/main/254/more-on-avoiding-ruby-keywords">blog entry</a> on this very topic.