如何在 Ruby 中列出一个对象的所有方法?

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

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

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

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

132565 次浏览

下面将列出 User 类具有的基对象类不具有的方法..。

>> 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是类和类实例的方法。

下面是我的 User 类中不在 ActiveRecord 基类中的方法:

>> 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 类中定义的(many) has _ many 关系创建的方法在 methods调用的结果中是 没有

新增 注意: has _ many 不直接添加方法。相反,ActiveRecord 机制使用 Rubymethod_missingresponds_to技术来动态处理方法调用。因此,methods方法结果中没有列出这些方法。

这个怎么样?

object.methods.sort
Class.methods.sort

模块 # instance _ method

返回一个数组,该数组包含接收方中的公共和受保护实例方法的名称。对于模块,它们是公共方法和受保护方法; 对于类,它们是实例(而不是单例)方法。如果没有参数,或者参数为 false,则返回 mod 中的实例方法,否则返回 mod 和 mod 的超类中的方法。

module A
def method1()  end
end
class B
def method2()  end
end
class C < B
def method3()  end
end


A.instance_methods                #=> [:method1]
B.instance_methods(false)         #=> [:method2]
C.instance_methods(false)         #=> [:method3]
C.instance_methods(true).length   #=> 43

你可以的

current_user.methods

为了更好的列表

puts "\n\current_user.methods : "+ current_user.methods.sort.join("\n").to_s+"\n\n"

假设用户有 _ many Posts:

u = User.first
u.posts.methods
u.posts.methods - Object.methods

阐述@clyfe 的回答。您可以使用以下代码获取实例方法的列表(假设您有一个名为“ Parser”的对象类) :

Parser.new.methods - Object.new.methods

如果您正在查看通过实例响应的方法列表(在您的例子中为@current _ user)。根据 Ruby 文档 方法

返回 obj 的公共和受保护方法的名称列表。 这将包括 obj 的祖先中可访问的所有方法 可选参数为 false,则返回 obj 的数组 公共和受保护的单例方法,数组将不包括 模块中的方法。

@current_user.methods
@current_user.methods(false) #only public and protected singleton methods and also array will not include methods in modules included in @current_user class or parent of it.

或者,您还可以检查方法是否可以对对象调用。

@current_user.respond_to?:your_method_name

如果你不想要父类方法,那么就从中减去父类方法。

@current_user.methods - @current_user.class.superclass.new.methods #methods that are available to @current_user instance.

或者只返回 User.methods(false),只返回在该类中定义的方法。