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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8595184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:31:29  来源:igfitidea点击:

How to list all methods for an object in Ruby?

ruby-on-railsruby

提问by Dirk

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

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

I have a @current_userobject, defined in the application controller:

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

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

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

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

回答by Larry K

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

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

>> 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", ...

Note that methodsis a method for Classes and for Class instances.

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

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

这是我的 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.

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

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

AddedNote that :has_many does not add methods directly. Instead, the ActiveRecord machinery uses the Ruby method_missingand responds_totechniques to handle method calls on the fly. As a result, the methods are not listed in the methodsmethod result.

添加注意 :has_many 不直接添加方法。相反,ActiveRecord 机制使用 Rubymethod_missingresponds_to技术来动态处理方法调用。因此,方法未在methods方法结果中列出。

回答by clyfe

Module#instance_methods

模块#instance_methods

Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. With no argument, or with an argument that is false, the instance methods in mod are returned, otherwise the methods in mod and mod's superclasses are returned.

返回一个包含接收器中公共和受保护实例方法名称的数组。对于模块,这些是公共和受保护的方法;对于一个类,它们是实例(不是单例)方法。如果没有参数,或者参数为假,则返回 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

回答by Ruto Collins

Or just User.methods(false)to return only the methods defined within that class.

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

回答by Andreas Lyngstad

You can do

你可以做

current_user.methods

For better listing

为了更好的上市

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

回答by Michael Frederick

What about one of these?

其中之一呢?

object.methods.sort
Class.methods.sort

回答by Marek P?íhoda

Suppose User has_many Posts:

假设用户 has_many 帖子:

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

回答by Jared Menard

To expound upon @clyfe's answer. You can get a list of your instance methods using the following code (assuming that you have an Object Class named "Parser"):

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

Parser.new.methods - Object.new.methods

回答by Mukesh Kumar Gupta

If You are looking list of methods which respond by an instance (in your case @current_user). According to ruby documentation methods

如果您正在查看由实例响应的方法列表(在您的情况下为@current_user)。根据 ruby​​ 文档方法

Returns a list of the names of public and protected methods of obj. This will include all the methods accessible in obj's ancestors. If the optional parameter is false, it returns an array of obj's public and protected singleton methods, the array will not include methods in modules included in obj.

返回 obj 的公共和受保护方法的名称列表。这将包括 obj 祖先中可访问的所有方法。如果可选参数为 false,则返回 obj 的公共和受保护单例方法的数组,该数组将不包含 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.

Alternatively, You can also check that a method is callable on an object or not?.

或者,您还可以检查某个方法是否可在对象上调用?。

@current_user.respond_to?:your_method_name

If you don't want parent class methods then just subtract the parent class methods from it.

如果您不想要父类方法,则只需从中减去父类方法即可。

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