Over a million developers have joined DZone.

Metaprogramming New Classes In Ruby

·
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 blog entry on this very topic.
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}