From 8e5a1520c80661c6997638b45e5050ff946d844d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stas=20SU=C8=98COV?= Date: Tue, 2 Nov 2021 22:50:54 +0000 Subject: Allow fetching class/module comments. --- lib/method_source.rb | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'lib') diff --git a/lib/method_source.rb b/lib/method_source.rb index 7d16c3b..3c6086b 100644 --- a/lib/method_source.rb +++ b/lib/method_source.rb @@ -121,6 +121,37 @@ module MethodSource def comment MethodSource.comment_helper(source_location, defined?(name) ? name : inspect) end + + # Return the comments associated with the method class/module. + # @return [String] The method's comments as a string + # @raise SourceNotFoundException + # + # @example + # MethodSource::MethodExtensions.method(:included).module_comment + # => + # # This module is to be included by `Method` and `UnboundMethod` and + # # provides the `#source` functionality + def class_comment + if self.respond_to?(:receiver) + class_inst_or_module = self.receiver + elsif self.respond_to?(:owner) + class_inst_or_module = self.owner + else + return comment + end + + if class_inst_or_module.respond_to?(:name) + const_name = class_inst_or_module.name + else + const_name = class_inst_or_module.class.name + class_inst_or_module = class_inst_or_module.class + end + + location = class_inst_or_module.const_source_location(const_name) + + MethodSource.comment_helper(location, defined?(name) ? name : inspect) + end + alias module_comment class_comment end end -- cgit v1.2.1