# Dynamic class creation at runtime

**URL:** <https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884>\
**Category:** Rails\
**Created:** [January 17, 2011, 11:02am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884 "2011-01-17T11:02:45Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![sempti](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/96bed5/32.png) [@sempti](https://www.ruby-forum.com/u/sempti)\
**Post date:** [January 17, 2011, 12:46pm UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/2 "2011-01-17T12:46:17Z")

</div>

On Jan 17, 10:02am, Sem P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> klass = Class.new(App) # uses App class to establish\_connection to  
> externalDB
> 
> klass = class\_eval do  
> #unsure about this. I need to set table\_name to same as class name  
> ActiveRecord::Base.set\_table\_name(“#{class\_name}”)  
> ActiveRecord::Base.const\_set(constant\_name, klass)  
> end # class\_eval

This sounds fishy, you’re calling set\_table\_name on AR::Base, not your  
class. just klass.set\_table\_name ‘blah’ should be enough

> # After creating the class - I want to establish an instance - but it
> 
> says that the class does not exist - more specifically constant doesn’t  
> exist.  
> eval(“#{table\_name} = #{class\_name}.new”)
> 
> I would love to hear thoughts on this, especially if I’m approaching  
> this incorrectly.

You haven’t created a constant called class\_name -  
ActiveRecord::Base.const\_set(constant\_name, klass) would have created  
ActiveRecord::Base::Foo.  
You probably wanted Object.const\_set class\_name, klass

Fred

---

_[View the full topic](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884)._
