module Code

Constants

VERSION

Public Class Methods

cruby_on_github(filename, line) click to toggle source
# 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) click to toggle source

Syntax highlight code string

# File lib/code.rb, line 29
def self.display(string, language = :ruby)
  puts CodeRay.scan(string, language).term
end
for(object = self, method_name) click to toggle source

API for end user

# 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 $!.message
end
from_docs(m) click to toggle source

Find C definition of Code

# 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) click to toggle source

Find Ruby definition of code

# 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