2013-01-07 17:12:10 -05:00
|
|
|
require 'pry/commands/code_collector'
|
|
|
|
|
2012-08-11 20:22:29 -04:00
|
|
|
class Pry
|
2012-12-25 16:35:17 -05:00
|
|
|
class Command::SaveFile < Pry::ClassCommand
|
|
|
|
match 'save-file'
|
2012-08-11 21:26:59 -04:00
|
|
|
group 'Input and Output'
|
2012-12-25 16:35:17 -05:00
|
|
|
description 'Export to a file using content from the REPL.'
|
2012-08-11 21:26:59 -04:00
|
|
|
|
2013-01-09 15:23:19 -05:00
|
|
|
banner <<-'BANNER'
|
2013-01-11 15:12:26 -05:00
|
|
|
Usage: save-file [OPTIONS] --to [FILE]
|
2013-01-09 15:23:19 -05:00
|
|
|
|
|
|
|
Export to a file using content from the REPL.
|
|
|
|
|
2013-01-11 15:12:26 -05:00
|
|
|
save-file my_method --to hello.rb
|
|
|
|
save-file -i 1..10 --to hello.rb --append
|
|
|
|
save-file show-method --to my_command.rb
|
|
|
|
save-file sample_file.rb --lines 2..10 --to output_file.rb
|
2013-01-09 15:23:19 -05:00
|
|
|
BANNER
|
2012-08-11 20:22:29 -04:00
|
|
|
|
2013-01-07 17:12:10 -05:00
|
|
|
def options(opt)
|
2013-01-08 19:39:02 -05:00
|
|
|
CodeCollector.inject_options(opt)
|
|
|
|
|
2013-01-11 15:12:26 -05:00
|
|
|
opt.on :to=, "Specify the output file path"
|
2013-01-09 15:23:19 -05:00
|
|
|
opt.on :a, :append, "Append output to file"
|
2012-08-11 20:22:29 -04:00
|
|
|
end
|
|
|
|
|
2013-01-07 17:12:10 -05:00
|
|
|
def process
|
2013-01-08 19:39:02 -05:00
|
|
|
@cc = CodeCollector.new(args, opts, _pry_)
|
|
|
|
raise CommandError, "Found no code to save." if @cc.content.empty?
|
2013-01-07 17:12:10 -05:00
|
|
|
|
2013-01-08 19:39:02 -05:00
|
|
|
if !file_name
|
2013-01-07 17:12:10 -05:00
|
|
|
display_content
|
2012-08-11 20:22:29 -04:00
|
|
|
else
|
2013-01-07 17:12:10 -05:00
|
|
|
save_file
|
2012-08-11 20:22:29 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2013-01-07 17:12:10 -05:00
|
|
|
def file_name
|
2013-01-08 19:39:02 -05:00
|
|
|
opts[:to] || nil
|
2012-08-11 20:22:29 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def save_file
|
|
|
|
File.open(file_name, mode) do |f|
|
2013-01-08 19:39:02 -05:00
|
|
|
f.puts @cc.content
|
2012-08-11 20:22:29 -04:00
|
|
|
end
|
2012-11-07 08:06:09 -05:00
|
|
|
output.puts "#{file_name} successfully saved"
|
2012-08-11 20:22:29 -04:00
|
|
|
end
|
|
|
|
|
2013-01-07 17:12:10 -05:00
|
|
|
def display_content
|
2013-01-08 19:39:02 -05:00
|
|
|
output.puts @cc.content
|
2013-01-07 17:12:10 -05:00
|
|
|
output.puts "\n\n--\nPlease use `--to FILE` to export to a file."
|
|
|
|
output.puts "No file saved!\n--"
|
|
|
|
end
|
|
|
|
|
2012-08-11 20:22:29 -04:00
|
|
|
def mode
|
2013-01-07 17:12:10 -05:00
|
|
|
opts.present?(:append) ? "a" : "w"
|
2012-08-11 20:22:29 -04:00
|
|
|
end
|
|
|
|
end
|
2012-12-25 16:35:17 -05:00
|
|
|
|
|
|
|
Pry::Commands.add_command(Pry::Command::SaveFile)
|
2012-08-11 20:22:29 -04:00
|
|
|
end
|