How to list all methods for an object in Ruby?

后端 未结 8 1933
北荒
北荒 2020-12-07 08:44

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

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



        
8条回答
  •  孤城傲影
    2020-12-07 09:24

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

    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.

    @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.
    

提交回复
热议问题