如何检索类名?

时间:2011-06-13 22:00:52

标签: ruby ruby-on-rails-3 class metaprogramming

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

BTW :我可以获得“常用”的其他“有用”信息吗?

3 个答案:

答案 0 :(得分:3)

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

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

修改

如果您确实想要查看更多元编程调用,请查看ObjectModule类的文档,并查看“Ruby Metaprogramming”的Google搜索结果。

答案 1 :(得分:2)

您是否尝试过class方法:

class A
  class B
  end
end

myobject = A::B.new

myobject.class

=> A::B

答案 2 :(得分:1)

要扩展@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