Module: Code
- Defined in:
- lib/code.rb,
lib/code/version.rb
Defined Under Namespace
Classes: NotFound
Constant Summary collapse
- VERSION =
"0.9.3".freeze
Class Method Summary collapse
- .cruby_on_github(filename, line) ⇒ Object
-
.display(string, language = :ruby) ⇒ Object
Syntax highlight code string.
-
.for(object = self, method_name) ⇒ Object
API for end user.
-
.from_docs(m) ⇒ Object
Find C definition of Code.
-
.from_ruby(m) ⇒ Object
Find Ruby definition of code.
Class Method Details
.cruby_on_github(filename, line) ⇒ Object
61 62 63 |
# File 'lib/code.rb', line 61 def self.cruby_on_github(filename, line) "https://github.com/ruby/ruby/blob/ruby_#{RUBY_VERSION[0]}_#{RUBY_VERSION[2]}/#{filename}#L#{line}" end |
.display(string, language = :ruby) ⇒ Object
Syntax highlight code string
29 30 31 |
# File 'lib/code.rb', line 29 def self.display(string, language = :ruby) puts CodeRay.scan(string, language).term end |
.for(object = self, method_name) ⇒ Object
API for end user
17 18 19 20 21 22 23 24 25 26 |
# File 'lib/code.rb', line 17 def self.for(object = self, method_name) m = object.method(method_name) begin from_ruby(m) rescue MethodSource::SourceNotFoundError from_docs(m) end rescue NameError, NotFound warn $!. end |
.from_docs(m) ⇒ Object
Find C definition of Code
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/code.rb', line 45 def self.from_docs(m) if RUBY_ENGINE != "ruby" raise Code::NotFound, "Method source not found for non-CRuby." elsif !defined?(CoreDocs) raise Code::NotFound, 'Method source not found. Might be possible with core_docs gem' elsif !(method_info = CoreDocs::MethodInfo.info_for(m)) raise Code::NotFound, 'Method source not found.' else source = method_info.source location = "//\n// #{cruby_on_github(method_info.file, method_info.line)}\n//\n" comment = method_info.docstring ? method_info.docstring.gsub(/^/, '// ') + "\n" : "" display location + comment + source, :c end end |
.from_ruby(m) ⇒ Object
Find Ruby definition of code
34 35 36 37 38 39 40 41 42 |
# File 'lib/code.rb', line 34 def self.from_ruby(m) source = m.source || "" indent = source.match(/\A +/) source = source.gsub(/^#{indent}/,"") comment = m.comment && !m.comment.empty? ? "#{ m.comment }" : "" location = m.source_location ? "#\n# #{ m.source_location*':' }\n#\n" : "" display location + comment + source end |