如何检索class级名称?

我正在使用Ruby on Rails 3.0.7,我想检索类名,如果它是命名空间的话。 例如,如果我有一个名为User::Profile::Manager我将使用一些未知的Ruby或Ruby on Rails方法并以安全的方式从中检索Manager字符串。

顺便说一句 :我可以获得哪些“常用”的“有用”信息?

一些有用的简单元编程调用:

 user = User::Profile::Manager.new(some_params) user.class # => User::Profile::Manager user.class.class # => Class user.class.name # => "User::Profile::Manager" user.class.name.class # => String # respond_to? lets you know if you can call a method on an object or if the method you specify is undefined user.respond_to?(:class) # => true user.respond_to?(:authenticate!) # => Might be true depending on your authentication solution user.respond_to?(:herpderp) # => false (unless you're the best programmer ever) # class.ancestors is an array of the class names of the inheritance chain for an object # In rails 3.1 it yields this for strings: "string".class.ancestors.each{|anc| puts anc} String JSON::Ext::Generator::GeneratorMethods::String Comparable Object PP::ObjectMixin JSON::Ext::Generator::GeneratorMethods::Object ActiveSupport::Dependencies::Loadable Kernel BasicObject 

如果你想要User::Profile::Manager的最低级别的类,我可能会做以下[使用正则表达式对我来说似乎有点过分;)]:

 user = User::Profile::Manager.new class_as_string = user.class.name.split('::').last # => "Manager" class_as_class = class_name.constantize # => Manager 

编辑:

如果您真的想要查看更多元编程调用,请查看对象和模块类的文档,并查看“Ruby Metaprogramming”的google结果。

你有没有尝试过class方法:

 class A class B end end myobject = A::B.new myobject.class => A::B 

要扩展@JCorcuera的答案,可以在kind_of中找到一些其他有用的信息? 和方法

 class A class B def foo end end end myobject = A::B.new p myobject.class => A::B p myobject.kind_of? A::B => true p myobject.methods => [:foo, :nil?, :===, :=~, ... p myobject.methods.include? :foo => true