Class: Dephine::CLI
- Inherits:
-
Object
- Object
- Dephine::CLI
- Defined in:
- lib/dephine/cli.rb
Overview
Public: Make a simple Command Line Interface. To use this class the ‘start’ class method should be called.
Examples
CLI.start(ARGV)
# => nil
Class Method Summary collapse
-
.define(arg) ⇒ Object
Internal: Display definitions of a word.
-
.play(audio) ⇒ Object
Public: Play word pronunciation.
-
.start(args) ⇒ Object
Public: Use cli arguments for running the application.
-
.which(cmd) ⇒ Object
Public: Cross-platform way of finding an executable in the $PATH.
Class Method Details
.define(arg) ⇒ Object
Internal: Display definitions of a word.
arg - The String that will be defined.
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 |
# File 'lib/dephine/cli.rb', line 53 def self.define(arg) word = Dephine::Dictionary.new(arg) if word.meanings.empty? abort("Word not found in the dictionary!") end t = Dephine::TUI.new t.puts arg word.meanings.each do |m| t.puts t.puts "#{m[:type].downcase} #{m[:phonetic]}" m[:meanings].each do |d| t.puts " #{d[:text]}" d[:examples].each do |eg| t.puts " - #{eg}" end t.puts end end if word.pronunciations.length > 0 # download pronunciation audio file open(word.pronunciations[0][:url]) pronunciation = OpenURI::Cache.send(:filename_from_url, word.pronunciations[0][:url]) # play pronunciation t.set_key 'p' do play(pronunciation) end end t.close end |
.play(audio) ⇒ Object
Public: Play word pronunciation. This method uses either mpg123 or afplay to play the audio file.
audio - The String that should be path of an audio file to be played.
45 46 47 48 |
# File 'lib/dephine/cli.rb', line 45 def self.play(audio) player = which('mpg123') || which('afplay') system("#{player} #{audio} 2>/dev/null") end |
.start(args) ⇒ Object
Public: Use cli arguments for running the application.
Returns nothing.
15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/dephine/cli.rb', line 15 def self.start(args) = [] << 'Dephine, Google dictionary in terminal' << 'Usage: dephine [word]' if args.empty? puts .join("\n") else define(args[0]) end end |
.which(cmd) ⇒ Object
Public: Cross-platform way of finding an executable in the $PATH.
which('ruby') #=> /usr/bin/ruby
30 31 32 33 34 35 36 37 38 39 |
# File 'lib/dephine/cli.rb', line 30 def self.which(cmd) exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each { |ext| exe = "#{path}/#{cmd}#{ext}" return exe if File.executable? exe } end return nil end |