Skip to content

Instantly share code, notes, and snippets.

@epitron
Last active September 25, 2015 15:37
Show Gist options
  • Save epitron/943954 to your computer and use it in GitHub Desktop.
Save epitron/943954 to your computer and use it in GitHub Desktop.
A require command that also prints out all the modules/classes that were loaded into Ruby!
def req(mod)
puts " |_ #{mod}"
require mod
yield if block_given?
rescue Exception => e
p e
end
## Fancy Require w/ Modules
req 'terminal-table/import' do
class Pry::Commands
command "require", "Requires gem(s). No need for quotes! (If the gem isn't installed, it will ask if you want to install it.)" do |*gems|
gems = gems.join(' ').gsub(',', '').split(/\s+/)
gems.each do |gem|
begin
before_modules = ObjectSpace.each_object(Module).to_a
if require gem
output.puts "#{bright_yellow(gem)} loaded"
loaded_modules = ObjectSpace.each_object(Module).to_a - before_modules
print_module_tree(loaded_modules)
else
output.puts "#{bright_white(gem)} already loaded"
end
rescue LoadError => e
if gem_installed? gem
output.puts e.inspect
else
output.puts "#{bright_red(gem)} not found"
if prompt("Install the gem?") == "y"
run "gem-install", gem
run "req", gem
end
end
end # rescue
end # gems
end
# command "ls", "List Stuff" do |*args|
# target.eval('self').meths(*args)
# end
def self.hash_mkdir_p(hash, path)
return if path.empty?
dir = path.first
hash[dir] ||= {}
hash_mkdir_p(hash[dir], path[1..-1])
end
def self.hash_print_tree(hash, indent=0)
result = []
dent = " " * indent
hash.each do |key,val|
result << dent+key
result += hash_print_tree(val, indent+1) if val.any?
end
result
end
def self.print_module_tree(mods)
mod_tree = {}
mods = mods.select { |mod| not mod < Exception }
mods = mods.map { |mod| mod.to_s.split("::") }
mods.sort.each do |path|
hash_mkdir_p(mod_tree, path)
end
results = hash_print_tree(mod_tree)
table = PrintMembers::Formatter::TableDefinition.new
results.each_slice(results.size / 3) do |slice|
table.column(*slice)
end
puts table(nil, *table.rows.to_a)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment