Class: Yatran::CLI

Inherits:
Object
  • Object
show all
Defined in:
lib/yatran/cli.rb

Instance Method Summary collapse

Constructor Details

#initializeCLI

Returns a new instance of CLI.



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
# File 'lib/yatran/cli.rb', line 34

def initialize()
  @options = {}
  languages = Yatran::LANGUAGES_TRANSLATIONS.join(',')
  OptionParser.new do |opts|
    opts.banner = <<EOS
              Yandex Command line translations.
              Available language directions : #{languages}
              Usage: yatran COMMAND [OPTIONS]

EOS
    opts.separator  ""
    opts.separator  "Commands"
    opts.separator  "     d: detect text language"
    opts.separator  "     t: translate text"
    opts.separator  ""
    opts.separator  "Options"
    opts.on( '-p', '--phrase Phrase [OPT]', "Phrase to translate or detect" ) do |source|
      @options[:text] = source
    end
    opts.on( '-s', '--source FILE [OPT]', "File with text to translate" ) do |source|
      @options[:file] = source
    end
    opts.on( '-o', '--output FILE [OPT]', "File with output" ) do |output|
      @options[:output] = output
    end
    opts.on("-f", "--from FROM_LANG [OPT]", "Language of phrase/text ") do |from|
      @options[:from] = from
    end
    opts.on("-t", "--to TO_LANG [OPT]", "Output language ") do |to|
      @options[:to] = to
    end
    opts.on("-l", "--language LANGDIR [OPT]", "Available language direction") do |d|
      @options[:direction] = d
    end
    opts.on( '-d', '--debug', "Debug flag" ) do
      @options[:debug] = true
    end
  end.parse!

end

Instance Method Details

#[](index) ⇒ Object



97
98
99
# File 'lib/yatran/cli.rb', line 97

def [](index)
   @options[index]
end

#detect!Object



92
93
94
95
# File 'lib/yatran/cli.rb', line 92

def detect!
  validate_text!
  puts "Detected: #{@text.language}"
end

#translate!Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/yatran/cli.rb', line 76

def translate!
  validate_text!
  validate_direction!
  result = @text.send(@direction)
  if @options[:output]
    raise Error.new("File #{@opts[:output]} already exists") if File.exists? @options[:output]
    File.open(@options[:output], 'w') { |f| f.write(result) }
    puts "check file #{@options[:output]}"

  else
    puts "Translated:"
    puts result
  end

end