Class: Ru::Process
- Inherits:
-
Object
- Object
- Ru::Process
- Defined in:
- lib/ru/process.rb
Instance Method Summary collapse
-
#initialize ⇒ Process
constructor
A new instance of Process.
- #run ⇒ Object
Constructor Details
#initialize ⇒ Process
Returns a new instance of Process.
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 |
# File 'lib/ru/process.rb', line 6 def initialize @options = {} @options_parser = OptionParser.new do |opts| opts. = <<-EOF Usage: ru [OPTION]... CODE FILE... cat FILE | ru [OPTION]... CODE echo CODE | ru [OPTION]... echo CODE | ru [OPTION]... '' [FILE...] EOF opts.on("-h", "Print usage help") do @options[:h] = true end opts.on("--help", "Print examples") do @options[:help] = true end opts.on("-v", "--version", "Print version") do @options[:version] = true end opts.on('-s', '--stream', 'Stream mode') do @options[:stream] = true end opts.on('-b', '--binary', 'Binary mode') do @options[:binary] = true end opts.on('--debug', 'Print debug messages') do @options[:debug] = true require 'logger' $debug = Logger.new($stderr) $debug.formatter = proc do |severity, _datetime, _progname, msg| "#{severity}: #{msg}\n" end end end @option_printer = OptionPrinter.new(options_parser: @options_parser) end |
Instance Method Details
#run ⇒ Object
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 |
# File 'lib/ru/process.rb', line 48 def run output = return output if output args = ARGV.dup code = args.shift.to_s parsed = prepare_code(code) { get_stdin(args, @options[:stream]) } $debug.debug parsed.inspect if $debug stdin = parsed[:stdin] if parsed[:code].empty? $debug.error "CODE is empty" if $debug $stderr.puts @option_printer.run(:h) exit false end context = if stdin.kind_of?(String) && stdin.empty? $debug.info "STDIN is empty" if $debug Ru::Array.new([]) else if @options[:stream] if @options[:binary] $debug.info "binary stream mode" if $debug Ru::Stream.new(stdin.each_byte.lazy) else $debug.info "text stream mode" if $debug Ru::Stream.new(stdin.each_line.lazy.map { |line| line.chomp("\n".freeze) }) end else if @options[:binary] $debug.info "binary mode" if $debug Ru::Array.new(stdin.bytes) else $debug.info "text mode" if $debug # Prevent 'invalid byte sequence in UTF-8' stdin.encode!('UTF-8', 'UTF-8', invalid: :replace) Ru::Array.new(stdin.split("\n")) end end end begin output = context.instance_eval(parsed[:code]) rescue NoMethodError $debug.info "loading active_support/all" if $debug require 'active_support/all' output = context.instance_eval(parsed[:code]) end prepare_output(output) end |