这是一个看似简单,实际不那么直接的问题。一种方法是先直接看当前对象的类是神马东东:
puts self.class 或者 self.class.name
不过在某些情况下上述代码返回不了具体的名称,前者返回一个<Class:xxx>后者返回nil;这是咋回事呢?原因是你在元类或称为单例类中,比如下面的情况:
class A; end
a=A.new
class<<a
puts a #like self.class
puts a.name #like self.class.name
end
那我怎么知道对象真正的类名呢?很简单,用ancestors方法!看似问题解决鸟,不过实际是很残酷的。我下面取得了某个类的所有祖先类和模块,你来告诉我一个名叫h的方法是在哪定义的:
[#<Class:0x007ff16ec3bbf0>, #<Module:0x007ff1699a2060>, #<Module:0x007ff169a8ba08>, ProjectsHelper, ApplicationHelper, #<Module:0x007ff169428d50>, ActionDispatch::Routing::RouteSet::MountedHelpers, #<Module:0x007ff16ec3bb50>, #<Module:0x007ff16d020038>, #<Module:0x007ff16d020060>, ActionView::RoutingUrlFor, ActionDispatch::Routing::UrlFor, ActionDispatch::Routing::PolymorphicRoutes, ActionController::ModelNaming, Turbolinks::XHRUrlFor, ActionView::Base, Sprockets::Rails::Helper, WebConsole::ViewHelpers, ActionView::Helpers, ActionView::Helpers::TranslationHelper, ActionView::Helpers::RenderingHelper, ActionView::Helpers::RecordTagHelper, ActionView::RecordIdentifier, ActionView::Helpers::FormHelper, ActionView::ModelNaming, ActionView::Helpers::NumberHelper, ActionView::Helpers::JavaScriptHelper, ActionView::Helpers::FormOptionsHelper, ActionView::Helpers::FormTagHelper, ActionView::Helpers::TextHelper, ActionView::Helpers::DebugHelper, ActionView::Helpers::SanitizeHelper, ActionView::Helpers::CacheHelper, ActionView::Helpers::AtomFeedHelper, ActionView::Helpers::UrlHelper, ActionView::Helpers::AssetTagHelper, ActionView::Helpers::AssetUrlHelper, ActionView::Helpers::ActiveModelHelper, ActiveSupport::Benchmarkable, ActionView::Helpers::TagHelper, ActionView::Helpers::OutputSafetyHelper, ActionView::Helpers::DateHelper, ActionView::Helpers::CsrfHelper, ActionView::Helpers::ControllerHelper, ActionView::Helpers::CaptureHelper, ERB::Util, ActionView::Context, ActionView::CompiledTemplates, Object, ActiveSupport::Dependencies::Loadable, PP::ObjectMixin, JSON::Ext::Generator::GeneratorMethods::Object, Kernel, BasicObject]
老大一坨嵌套啊!别笑,这是一个真实环境中的例子,确切的说是rails中的例子。要想知道h在哪里定义的我们可以用如下方法:
<% self.class.ancestors.each do |a| %> <% unless a.methods(false).select {|m|m=~/^h$/}.empty?%> <p><%= a.name%></p> <% end %> <% end %>
如果h不是public方法的话,也很简单,把a.methods改为a.xxx_methods就可以鸟,有些时候就是要碰运气的哦!比如上面几行代码很快返回了结果:ERB::Util,虽然用ri ERB::Util#h还是不知道h是干嘛的...
好吧,知道了,h是html_escape的简写