Skip to content

Instantly share code, notes, and snippets.

@bmabey
Forked from lsegal/snippet.rb
Created April 6, 2010 05:40
Show Gist options
  • Save bmabey/357257 to your computer and use it in GitHub Desktop.
Save bmabey/357257 to your computer and use it in GitHub Desktop.
# In a clojure REPL you can get information about a function like so:
# user=> (doc identity)
# -------------------------
# clojure.core/identity
# ([x])
# Returns its argument.
# nil
# user=> (source identity)
# (defn identity
# "Returns its argument."
# [x] x)
# nil
#
# I've become very dependent on these helpers when writing clojure.
# I want this same goodness in IRB when I'm hacking ruby code. This is a
# proof of concept of using YARD to get #source and #doc helpers in IRB.
# This requires ruby 1.9 and the latest version of YARD. See this gist for
# 1.8 compat: http://gist.github.com/357264
#
#
# Many thanks to lsegal for making this so simple with YARD and showing me
# how to do it.
require 'yard'
module YardObject
def source; yard_object.source end
def docstring; yard_object.docstring end
private
def yard_object
fname = source_location[0]
@@file_cache ||= {}
unless @@file_cache[fname]
@@file_cache[fname] = true
YARD.parse(fname)
end
@yard_object ||= YARD::Registry.at(owner.name + '#' + name.to_s)
end
end
class Method; include YardObject end
class UnboundMethod; include YardObject end
class Foo
# This is a very cool method. It does a ton.
def bar
puts "Hello!" # Stuff
end
end
def source(method_signature)
yard_info(method_signature, :source)
end
def doc(method_signature)
yard_info(method_signature, :docstring)
end
def yard_info(method_signature, info)
puts "-------------------------"
puts method_signature
puts YARD::Registry.at(method_signature).send(info)
end
f = Foo.new
puts f.method(:bar).docstring
puts f.method(:bar).source
# This is a very cool method. It does a ton.
# def bar
# puts "Hello!" # Stuff
# end
#
puts "\n\nIRB session with this goodness\n\n"
puts "doc \"Foo#bar\""
puts doc("Foo#bar")
puts "\n\n\n"
puts "source \"Foo#bar\""
puts source("Foo#bar")
puts ""
# IRB session with this goodness
#
# doc "Foo#bar"
# -------------------------
# Foo#bar
# This is a very cool method. It does a ton.
#
# source "Foo#bar"
# -------------------------
# Foo#bar
# def bar
# puts "Hello!" # Stuff
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment