列出子类在 Ruby 脚本/控制台中不起作用? [英] Listing subclasses doesn't work in Ruby script/console?

查看:36
本文介绍了列出子类在 Ruby 脚本/控制台中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有效:

>> class Foo 
>>   def xyz()
>>     Foo.subclasses
>>   end
>> end
=> nil
>> class Bar < Foo
>> end
=> nil
>> class Quux < Bar
>> end
=> nil
>> Foo.new.xyz()
=> ["Quux", "Bar"]

但这不是.User 是我的应用程序中的一个类.

But this doesn't. User is a class in my application.

>> User.subclasses
NoMethodError: protected method `subclasses' called for #<Class:0x20b5188>
    from [...]/vendor/rails/activerecord/lib/active_record/base.rb:1546:in `method_missing'
    from (irb):13

但确实如此!

>> Foo.subclasses
=> ["Quux", "Bar"]

这是怎么回事?我将如何列出 User 的子类?

What's going on here? How would I list the subclasses of User?

推荐答案

subclasses 在 base.rb 中被覆盖和保护.参见 http://www.google.com/codesearch/p?hl=en&sa=N&cd=1&ct=rc#m8Vht-lU3vE/vendor/rails/activerecord/lib/active_record/base.rb&q=active_record/base.rb(第 1855 行定义方法子类,第 1757 行使其受到保护).

subclasses is overridden and made protected in base.rb. See http://www.google.com/codesearch/p?hl=en&sa=N&cd=1&ct=rc#m8Vht-lU3vE/vendor/rails/activerecord/lib/active_record/base.rb&q=active_record/base.rb (line 1855 defines method subclasses, line 1757 makes it protected).

您可以对 User 执行与对 Foo 执行相同的操作:添加 xyz() 方法.

You could do the same for User as you did for Foo: add a xyz() method.

这篇关于列出子类在 Ruby 脚本/控制台中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆