如何在 Ruby 中列出对象的所有方法? [英] How to list all methods for an object in Ruby?

查看:55
本文介绍了如何在 Ruby 中列出对象的所有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何列出特定对象有权访问的所有方法?

How do I list all the methods that a particular object has access to?

我有一个 @current_user 对象,在应用程序控制器中定义:

I have a @current_user object, defined in the application controller:

def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

并且想看看我在视图文件中有哪些可用的方法.具体来说,我想看看 :has_many 关联提供了哪些方法.(我知道 :has_many 应该提供什么,但想检查一下.)

And want to see what methods I have available to me in the view file. Specifically, I want to see what methods a :has_many association provides. (I know what :has_many should provide, but want to check that.)

推荐答案

下面将列出 User 类有而 Object 基类没有的方法...

The following will list the methods that the User class has that the base Object class does not have...

>> User.methods - Object.methods
=> ["field_types", "maximum", "create!", "active_connections", "to_dropdown",
    "content_columns", "su_pw?", "default_timezone", "encode_quoted_value", 
    "reloadable?", "update", "reset_sequence_name", "default_timezone=", 
    "validate_find_options", "find_on_conditions_without_deprecation", 
    "validates_size_of", "execute_simple_calculation", "attr_protected", 
    "reflections", "table_name_prefix", ...

请注意,methods 是用于类和类实例的方法.

Note that methods is a method for Classes and for Class instances.

以下是我的 User 类具有但不在 ActiveRecord 基类中的方法:

Here's the methods that my User class has that are not in the ActiveRecord base class:

>> User.methods - ActiveRecord::Base.methods
=> ["field_types", "su_pw?", "set_login_attr", "create_user_and_conf_user", 
    "original_table_name", "field_type", "authenticate", "set_default_order",
    "id_name?", "id_name_column", "original_locking_column", "default_order",
    "subclass_associations",  ... 
# I ran the statements in the console.

请注意,由于 User 类中定义的(许多)has_many 关系而创建的方法出现在 methods 调用的结果中.

Note that the methods created as a result of the (many) has_many relationships defined in the User class are not in the results of the methods call.

已添加 请注意 :has_many 不直接添加方法.相反,ActiveRecord 机制使用 Ruby method_missingresponds_to 技术来动态处理方法调用.因此,methods 方法结果中未列出这些方法.

Added Note that :has_many does not add methods directly. Instead, the ActiveRecord machinery uses the Ruby method_missing and responds_to techniques to handle method calls on the fly. As a result, the methods are not listed in the methods method result.

这篇关于如何在 Ruby 中列出对象的所有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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