Module: Code
- Defined in:
- lib/code.rb,
lib/code/version.rb
Defined Under Namespace
Classes: NotFound
Constant Summary collapse
- VERSION =
"0.9.4"
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
66 67 68 |
# File 'lib/code.rb', line 66 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
34 35 36 |
# File 'lib/code.rb', line 34 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 27 28 29 30 31 |
# File 'lib/code.rb', line 17 def self.for(object = self, method_name) if method_name.is_a?(Method) || method_name.is_a?(UnboundMethod) m = method_name else m = object.method(method_name) end 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
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/code.rb', line 50 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
39 40 41 42 43 44 45 46 47 |
# File 'lib/code.rb', line 39 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 |