我使用的是RubyonRails 3.0.7,我想检索类名,如果它是有名称空间的。例如,如果我有一个名为User::Profile::Manager
的类,我会使用一些我不知道的Ruby或RubyonRails方法,并以安全的方式从中检索Manager
字符串。
BTW:我还可以为该类获得哪些"常用"的"有用"信息?
一些有用的简单元编程调用:
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
编辑:
如果你真的想查看更多的元编程调用,请查看Object和Module类的文档,并查看"Ruby元编程"的谷歌结果。
您尝试过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