Over a million developers have joined DZone.

Metaprogramming New Classes In Ruby

DZone's Guide to

Metaprogramming New Classes In Ruby

Free Resource
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.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}