[英]how to list all the methods available for a given object in ruby but not the inbuilt ones
[英]How to list all methods for an object in Ruby?
如何列出特定對象可以訪問的所有方法?
我有一個@current_user
對象,在應用程序控制器中定義:
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
並希望在視圖文件中查看我可以使用的方法。 具體來說,我想看看a :has_many
關聯提供了哪些方法。 (我知道:has_many
應該提供什么,但想檢查一下。)
以下將列出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", ...
請注意, 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類中定義的(許多)has_many關系而創建的方法不在 methods
調用的結果中。
添加注意:has_many不直接添加方法。 相反,ActiveRecord機制使用Ruby method_missing
和responds_to
技術來動態處理方法調用。 因此, 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
或者只是User.methods(false)
只返回該類中定義的方法。
你可以做
current_user.methods
為了更好的上市
puts "\n\current_user.methods : "+ current_user.methods.sort.join("\n").to_s+"\n\n"
其中一個怎么樣?
object.methods.sort
Class.methods.sort
闡述@ clyfe的答案。 您可以使用以下代碼獲取實例方法的列表(假設您有一個名為“Parser”的對象類):
Parser.new.methods - Object.new.methods
如果您正在查看按實例響應的方法列表(在您的情況下為@current_user)。 根據ruby文檔方法
返回obj的public方法和受保護方法的名稱列表。 這將包括obj的祖先可訪問的所有方法。 如果可選參數為false,則返回obj的public和protected singleton方法的數組,該數組將不包含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.
假設用戶has_many帖子:
u = User.first
u.posts.methods
u.posts.methods - Object.methods
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.