Skip to content

Instantly share code, notes, and snippets.

@banister
Created November 20, 2012 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save banister/4115151 to your computer and use it in GitHub Desktop.
Save banister/4115151 to your computer and use it in GitHub Desktop.
Pry::Commands.create_command "bookmark" do
group 'bookmark'
description "Bookmark stuff."
banner <<-USAGE
Usage: bookmark [OPTIONS]
Bookmark repl content.
USAGE
def options(opt)
opt.on :a, :add, "Add a bookmark (and an optional note).", :argument => true
opt.on :s, :show, "Show a bookmark and any notes.", :argument => true
opt.on :l, :list, "List all bookmarked objects."
end
def setup
if !state.added_reminders
add_reminders
state.added_reminders = true
end
end
def notes
state.bookmarks ||= {}
end
# edit a note in a temporary file and return note content
def edit_note(obj_name)
temp_file do |f|
f.puts("Enter note content here for #{obj_name} (and erase this line)")
f.flush
f.close(false)
invoke_editor(f.path, 1, false)
File.read(f.path)
end
end
def process
if opts.present?(:add)
add_bookmark(opts[:a])
elsif opts.present?(:show)
show_bookmark(opts[:s])
elsif opts.present?(:list)
list_bookmarks
end
end
def retrieve_code_object_safely(name)
code_object = retrieve_code_object_from_string(name, target)
if code_object.name.to_s == ""
raise Pry::CommandError, "Object #{name} doesn't have a proper name, can't create bookmark"
end
code_object
end
def code_object_name(co)
co.is_a?(Pry::Method) ? co.name_with_owner : co.name
end
def add_bookmark(name)
co_name = code_object_name(retrieve_code_object_safely(name))
note = edit_note(co_name)
notes[co_name] ||= []
notes[co_name] << note
end
def show_bookmark(name)
code_object = retrieve_code_object_safely(name)
output.puts "Showing note(s) for #{code_object.name}:"
notes[code_object_name(code_object)].each_with_index do |note, index|
output.puts "\nNote #{index + 1}:\n--"
output.puts note
end
end
def list_bookmarks
output.puts "Showing all available bookmarks:\n\n"
notes.each do |key, content|
output.puts "#{key} has #{content.count} notes"
end
output.puts "\nTo view notes for a bookmarked item type, e.g: `bookmark -s Klass#method`"
end
def add_reminders
me = self
reminder = proc do
begin
code_object = retrieve_code_object_from_string(args.first.to_s, target)
if me.notes.keys.include?(me.code_object_name(code_object))
co_name = me.code_object_name(code_object)
bolded_text = text.bold "#{me.notes[co_name].count} notes"
output.puts "\n\n#{text.bold("Notes:")}\n--\n\nThere are #{bolded_text} for this object. Type `bookmark -s #{co_name}` to view them."
end
rescue
end
end
Pry.commands.after_command("show-source", &reminder)
Pry.commands.after_command("show-doc", &reminder)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment