# 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:** 17\
**Page:** 1

<div class="post-metadata">

**Author:** ![luislavena](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/0ea827/32.png) [@luislavena](https://www.ruby-forum.com/u/luislavena)\
**Post date:** [January 17, 2011, 11:02am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/1 "2011-01-17T11:02:45Z")

</div>

I have a scenario where I need to dynamically create classes from  
existing application (external to app) databases, to pull data for  
reports.

# Table definitions

APP\_TABLES = %w(#list of tables for a given app - I’m sure I could  
query this on a simple connect. But let’s stick to this for now.)

APP\_TABLES.each do |table\_name|

# camelize for class creation

class\_name = table\_name.camelize

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

# 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.

---

<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

---

<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, 3:09pm UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/3 "2011-01-17T15:09:25Z")

</div>

On Jan 17, 12:44pm, Sem P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> klass = class\_eval do  
> set\_table\_name(“#{class\_name}”) or puts “Class set table name  
> failed”  
> Object.const\_set(constant\_name, klass) or puts “Class name  
> constant set failed”  
> end # class\_eval
> 
> but get an unknown method error on the set\_table\_name call.

you don’t need the class\_eval . just klass.set\_table\_name should work  
(I don’t think the method is protected, if it is you might have to use  
send)

> The App class (below) inherits from ActiveRecord::Base which in turn  
> should have that method.
> 
> class App \< ActiveRecord::Base  
> abstract\_class = true

this should be self.abstract\_class = true (right now you’re just  
setting a local variable)

> def initialize  
> establish\_connection :app\_development  
> end

This is dodgy. First of all you’re overriding initialize, but without  
calling through to the super class, so your activerecord objects won’t  
get initialized properly. You’ve also change the signature of  
initialize. Also, do you really want to be reconnecting to the  
database everytime a new instance is created? lastly this  
establish\_connection is a class method

---

<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, 1:44pm UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/4 "2011-01-17T13:44:20Z")

</div>

Thanks for the reply.

Frederick C. wrote in post #975422:

> > 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

True. I receive an unknown method error though.

> > eval(“#{table\_name} = #{class\_name}.new”)  
> > You haven’t created a constant called class\_name -  
> > You probably wanted Object.const\_set class\_name, klass

Sorry - I seem to have missed posting the  
class\_name = table\_name.camelize  
line in there (have large sections of comments that I didn’t want to  
clutter the post).

I’ve changed the above code to:

APP\_TABLES.each do |table\_name|  
class\_name = table\_name.camelize  
klass = Class.new(App)  
constant\_name = “#{class\_name}”

```
klass = class_eval do
  set_table_name("#{class_name}") or puts "Class set table name

```

failed"  
Object.const\_set(constant\_name, klass) or puts “Class name  
constant set failed”  
end # class\_eval

but get an unknown method error on the set\_table\_name call.

The App class (below) inherits from ActiveRecord::Base which in turn  
should have that method.

class App \< ActiveRecord::Base  
abstract\_class = true

def initialize  
establish\_connection :app\_development  
end

# to avoid trying to connect to the external app table by default

def self.columns() @columns ||= ; end  
end

---

<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, 3:20pm UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/5 "2011-01-17T15:20:43Z")

</div>

Frederick C. wrote in post #975445:

> On Jan 17, 12:44pm, Sem P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:
> 
> > class App \< ActiveRecord::Base  
> > abstract\_class = true
> 
> this should be self.abstract\_class = true (right now you’re just  
> setting a local variable)

Point taken.

> > def initialize  
> > establish\_connection :app\_development  
> > end
> 
> This is dodgy. First of all you’re overriding initialize, but without  
> calling through to the super class, so your activerecord objects won’t  
> get initialized properly.  
> Taken from online suggestions for handling multiple DBs.

> You’ve also change the signature of  
> initialize. Also, do you really want to be reconnecting to the  
> database everytime a new instance is created? lastly this  
> establish\_connection is a class method

Thanks. I’ll fix all that and get back to you.

---

<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 18, 2011, 7:31am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/6 "2011-01-18T07:31:44Z")

</div>

# APP\_TABLES contain a list of table names - would be better to

dynamically read them after connecting

APP\_TABLES.each do |table\_name|  
class\_name = table\_name.camelize  
klass = Class.new(App)  
constant\_name = “#{class\_name}”

# even though klass is created with App as superclass (inheriting from

ActiveRecord::Base, the set\_table\_name seems to be unavailable - what am  
I missing here?  
klass.set\_table\_name ("#{class\_name}") or puts “Class set table name  
failed”  
klass.const\_set(constant\_name, klass) or puts “Class name constant set  
failed”  
eval("#{table\_name} = #{class\_name}.new") or puts “Class instantiation  
failed”  
end

How can I determine if the klass has actually been created?  
How long will the dynamic classes exist in memory?  
For the duration of this rake task execution?  
Is there a way to list classes created at runtime?

---

<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 18, 2011, 8:25am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/7 "2011-01-18T08:25:36Z")

</div>

On Jan 18, 6:31am, Sem P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I missing here?  
> what happens when you try?

> klass.set\_table\_name (“#{class\_name}”) or puts “Class set table name  
> failed”  
> klass.const\_set(constant\_name, klass) or puts “Class name constant set  
> failed”  
> eval(“#{table\_name} = #{class\_name}.new”) or puts “Class instantiation  
> failed”  
> end
> 
> How can I determine if the klass has actually been created?

I don’t think Class.new can actually fail

> How long will the dynamic classes exist in memory?

> For the duration of this rake task execution?  
> Is there a way to list classes created at runtime?

I think that klass exists much like any variable - it may be garbage  
collected if nothing references it (classes might be special though) .  
You can step through objects of any class (including Class) via  
objectspace, although you probably won’t be able to distinguish  
classes created like this from other classes.

Fred

---

<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 18, 2011, 8:55am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/8 "2011-01-18T08:55:37Z")

</div>

Thanks for your repeated answers.

Frederick C. wrote in post #975619:

> what happens when you try?

Class set table name failed

---

<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 18, 2011, 12:29pm UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/9 "2011-01-18T12:29:25Z")

</div>

On Jan 18, 7:55am, Sem P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Thanks for your repeated answers.
> 
> Frederick C. wrote in post #975619:
> 
> > what happens when you try?
> 
> Class set table name failed

That’s just what you’re printing out - the return value of  
set\_table\_name isn’t documented, so i wouldn’t assume nil or false to  
mean failure

Fred

---

<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 19, 2011, 9:05am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/10 "2011-01-19T09:05:03Z")

</div>

Frederick C. wrote in post #975672:

> That’s just what you’re printing out - the return value of  
> set\_table\_name isn’t documented, so i wouldn’t assume nil or false to  
> mean failure

OK, so I’m down to:

class ExternalApp \< ActiveRecord::Base  
self.abstract\_class = true  
establish\_connection :external\_app  
def self.columns() @columns ||= ; end  
end

#App tables has a list of tables in external app, until I get this bit  
working  
APP\_TABLES.each do |table\_name|  
constant\_name = class\_name = table\_name.camelize  
klass = Class.new(ExternalApp)  
klass.set\_table\_name(“#{class\_name}”)  
klass.const\_set(constant\_name, klass)  
eval(“#{table\_name} = #{class\_name}.new”) or puts “Class instantiation  
failed”  
end

On running this rake task I get the following error:

lib/rspec/core/backward\_compatibility.rb:20:in `const\_missing’:  
uninitialized constant Services

Is const\_set where the klass name is ‘set in stone’?

---

<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 19, 2011, 9:14am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/11 "2011-01-19T09:14:47Z")

</div>

On 19 Jan 2011, at 08:05, Sem P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> On running this rake task I get the following error:
> 
> lib/rspec/core/backward\_compatibility.rb:20:in `const\_missing’:  
> uninitialized constant Services
> 
> Is const\_set where the klass name is ‘set in stone’?

It is, but you’re using it back to front: klass.const\_set sets a  
constant on klass, whereas you want to set a top level constant ie  
Object.const\_set

Fred.

---

<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 19, 2011, 9:20am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/12 "2011-01-19T09:20:46Z")

</div>

Frederick C. wrote in post #975964:

> It is, but you’re using it back to front: klass.const\_set sets a  
> constant on klass, whereas you want to set a top level constant ie  
> Object.const\_set

That makes sense, thought it might be a scope problem.

Thank you.

---

<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 19, 2011, 9:59am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/13 "2011-01-19T09:59:26Z")

</div>

Frederick C. wrote in post #975964:

> It is, but you’re using it back to front: klass.const\_set sets a  
> constant on klass, whereas you want to set a top level constant ie  
> Object.const\_set

You are my personal hero, today. Thank you so much for helping out on  
this thread. It works.

---

<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 19, 2011, 9:35am UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/14 "2011-01-19T09:35:12Z")

</div>

Ok, so this seems to work

1. Create dynamic classes from a list (some rework on getting that from  
tables automatically needed)
2. Instantiate those objects

A minor error pops up now.

The tables exist, as do the fields.

However, with:

service = Services.new(:portID =\> 333, :method =\> “PUT”)

But I get the error:

unknown attribute: portID

---

<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 19, 2011, 12:02pm UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/15 "2011-01-19T12:02:10Z")

</div>

On Jan 19, 8:35am, Sem P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> The tables exist, as do the fields.
> 
> However, with:
> 
> service = Services.new(:portID =\> 333, :method =\> “PUT”)
> 
> But I get the error:
> 
> unknown attribute: portID

Probably the result of you suppressing the columns method. If AR  
things there are no columns, it will think there are no attributes

Fred

---

<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 19, 2011, 12:37pm UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/16 "2011-01-19T12:37:55Z")

</div>

Frederick C. wrote in post #975987:

> Probably the result of you suppressing the columns method. If AR  
> things there are no columns, it will think there are no attributes

From the superclass. Right. Thanks.

---

<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 19, 2011, 1:15pm UTC](https://www.ruby-forum.com/t/dynamic-class-creation-at-runtime/201884/17 "2011-01-19T13:15:28Z")

</div>

Everything’s perfect now. Thanks again for the repeated replies.
