Jay*_*rio 4 ruby ruby-on-rails ruby-on-rails-3.2 ruby-2.2
使用Ruby 2.2.1,如何列出仅在该类/文件中定义的类的所有方法(最好是字符串数组),其中include和extend方法被过滤掉.我想区分类和实例方法.
目前,我可以使用所有未使用的MyClass.methods(false)方法,但这仍然包括作为include模块一部分的方法.
明确地说,我有:
class MyClass < BaseClass
extend AnotherBaseClass
include MyModule
def foo
end
def bar
end
end
Run Code Online (Sandbox Code Playgroud)
我想得到:
somecodethatreturnssomething
#=> ['foo', 'bar']
# Not including BaseClass, AnotherBaseClass, and ModuleClass methods
Run Code Online (Sandbox Code Playgroud)
更新:
当我在一个单独的irb控制台中运行它时,@ Waker Maker的答案是正确的.不过,我仍然有一个问题,特别是我,包括ActionView::Helpers::UrlHelper在MyClass.我总是得到额外的方法:default_url_options?,default_url_options=,和default_url_options.我认为无论Rails与否都包含相同的行为,所以我没有用Rails标记这个问题.
我甚byebug至在文件的末尾添加了MyClass,以便我可以检查类并运行MyClass.singleton_methods(false)或运行MyClass.instance_methods(false).但他们仍然包括这三种不需要的方法.
我可以手动从数组中删除这三个额外的方法,所以我可以得到我的类的方法的动态列表,但我只是害怕将来我的应用程序将破坏,如果有更新或将添加新方法的东西班级(不知不觉).
更新:
这3种方法只在Rails 3(我正在研究的项目)中添加,但不在Rails 4中(因为我和@Wand Maker已经测试过).
这是确切的代码(我已经删除了所有内容,但仍然得到相同的结果/问题)
# lib/my_class.rb
class MyClass
include ActionView::Helpers::UrlHelper
def welcome
puts 'Hello Jules!'
end
def farewell
puts 'Goodbye Jules!'
end
end
byebug
Run Code Online (Sandbox Code Playgroud)
或者我可以删除该文件:my_class.rb(并复制并粘贴整个代码rails console)
但是,仍然遇到同样的问题.
Wan*_*ker 10
您可以执行以下操作:
MyClass.instance_methods(false)
#=> [:foo, :bar]
Run Code Online (Sandbox Code Playgroud)
如果要包含任何定义的类方法MyClass,可以执行以下操作:
MyClass.instance_methods(false) + MyClass.singleton_methods(false)
Run Code Online (Sandbox Code Playgroud)
这是定义所有类/模块的工作示例
class BaseClass
def moo
end
end
module AnotherBaseClass
def boo
end
end
module MyModule
def roo
end
end
class MyClass < BaseClass
extend AnotherBaseClass
include MyModule
def self.goo
end
def foo
end
def bar
end
end
p MyClass.instance_methods(false) + MyClass.singleton_methods(false)
#=> [:foo, :bar, :goo]
p RUBY_VERSION
#=> "2.2.2"
Run Code Online (Sandbox Code Playgroud)