Alex Rivera | Logout

Ruby String to Class Name

Asked 2011-03-14T17:37:00.860
39

I am trying to create a new class to that will inherit from ActiveRecord::Base the class needs to be dynamically generated from a string

"general_systems".camelize.singularize = Class.new < ActiveRecord::Base

However I keep getting the error:

undefined method `singularize=' for "GeneralSystems":String

I've also tried to constantize the string

>> foo = "general_systems".camelize.singularize
=> "GeneralSystem"
>> foo.constantize
NameError: uninitialized constant GeneralSystem
    from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/inflector/methods.rb:124:in `block in constantize'
    from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/inflector/methods.rb:123:in `each'
    from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/inflector/methods.rb:123:in `constantize'
    from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/core_ext/string/inflections.rb:43:in `constantize'
    from (irb):4
    from /usr/bin/irb:12:in `<main>'
>> foo.constantize = Class.new
NoMethodError: undefined method `constantize=' for "GeneralSystem":String
    from (irb):5
    from /usr/bin/irb:12:in `<main>'

Any help would be greatly appreciated.

Edit
Report

2 Answers

34

Something like this?

>> Object.const_set("general_systems".classify, Class.new)
=> GeneralSystem
>> GeneralSystem.new
=> #<GeneralSystem:0x105b0f738>
answered 2011-03-14T17:45:20.883
8

Look at this example from "The Book Of Ruby", included in the Ruby 1.9 installer.

puts("What shall we call this class?> ")
className = gets.strip().capitalize()
Object.const_set(className,Class.new)
puts("I'll give it a method called > 'myname'" ) 
className = Object.const_get(className)
className::module_eval{
  define_method(:myname){ 
    puts("The name of my class is '#{self.class}'" ) 
 } }
 x = className.new x.myname
answered 2011-03-14T17:45:12.447

Your Answer