Last active
April 12, 2017 20:03
-
-
Save mklbtz/a396536936da7607bac5a6e0fc3779e2 to your computer and use it in GitHub Desktop.
Helper methods for inspecting your methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Object | |
# List Methods defined directly in the receiver's class. | |
def my_methods | |
methods_from(self.class) | |
end | |
# List Methods with names matching the regex. | |
def methods_matching(regex) | |
methods_where { |meth| regex.match(meth.name.to_s) } | |
end | |
# Filter Methods by block. | |
# The block receives Method objects, not just their names. | |
def methods_where(&block) | |
methods.keep_if { |name| block.call(method(name)) } | |
end | |
# object.methods_from SomeModule | |
# List Methods defined in SomeModule | |
# | |
# object.methods_from /Some/ | |
# List Methods defined in a module whose name matches the regex. | |
# Useful for finding methods from multiple modules in the same gem. (e.g. /^ActiveRecord/) | |
def methods_from(source) | |
if source.is_a? Regexp | |
methods_where { |meth| source.match(String(meth.owner)) } | |
else | |
methods_where { |meth| meth.owner == source } | |
end | |
end | |
# Find methods defined by attr_* | |
def attr_methods | |
methods_where do |meth| | |
meth.arity < 2 && | |
meth.source_location && | |
(source = meth.source rescue nil) && | |
/attr_(reader|writer|accessor)/.match(source) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment