Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby String to Class Name

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.

like image 307
Telmo Avatar asked Mar 14 '11 17:03

Telmo


People also ask

How do I find the class of an object in Ruby?

Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false . #is_a also returns true if the object is an instance of any subclasses.

What is IS_A in Ruby?

The is_a? method will return a true value if an object is a of the type given as a parameter OR if it inherits from the type given as a parameter. So in effect, you can use it to ask "is there going to be a method from a class which I can run on this object".

How do you use the Replace method in Ruby?

First, you don't declare the type in Ruby, so you don't need the first string . To replace a word in string, you do: sentence. gsub(/match/, "replacement") .

How do you check the type of a variable in Ruby?

The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object. class . Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.


1 Answers

If you're using Rails, it provides a method called #constantize that will work:

irb(main):017:0> Object.const_get 'House::Owns' NameError: wrong constant name House::Owns  'House::Owns'.constantize => House::Owns 
like image 79
Peter Ehrlich Avatar answered Sep 19 '22 17:09

Peter Ehrlich