Alex Rivera | Logout

How do I get class-object from string "A::B::C" in Ruby?

Asked 2010-07-23T00:08:58.083
9

The following example fails

class A
  class B
  end
end
p Object.const_get 'A' # => A
p Object.const_get 'A::B' # => NameError: wrong constant name A::B

UPDATE

Questions about the topic asked earlier:

  1. Cast between String and Classname
  2. Ruby String#to_class
  3. Get a class by name in Ruby?

The last one gives a nice solution which can be evolved into

class String
  def to_class
    self.split('::').inject(Object) do |mod, class_name|
      mod.const_get(class_name)
    end
  end
end

class A
  class B
  end
end
p "A::B".to_class # => A::B
Edit
Report

1 Answer

0

Extlib provides a full_const_get method, which does just this.

http://github.com/datamapper/extlib/blob/master/lib/extlib/object.rb#L67

You could either include extlib, or copy this implementation and use it yourself (assuming the licensing is compatible with whatever you're using it for)

answered 2010-07-23T13:23:05.240

Your Answer