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

Dir*_*irk 102 ruby ruby-on-rails

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

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

def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end
Run Code Online (Sandbox Code Playgroud)

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

Lar*_*y K 191

以下将列出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", ...
Run Code Online (Sandbox Code Playgroud)

请注意,这methods是Classes和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.
Run Code Online (Sandbox Code Playgroud)

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

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

  • 虽然这可能不完整,因为只有在调用method_missing时才会创建一些方法(例如动态查找程序) (2认同)

cly*_*yfe 9

模块#instance_methods

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


Rut*_*ins 6

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


And*_*tad 5

你可以做

current_user.methods
Run Code Online (Sandbox Code Playgroud)

为了更好的上市

puts "\n\current_user.methods : "+ current_user.methods.sort.join("\n").to_s+"\n\n"
Run Code Online (Sandbox Code Playgroud)