public
Created

  • Download Gist
bookmark.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.