Sha256: 708342676f30d31264c7abc986e41747bdc157118b7e6a27c018b9ec3e2ea590

Contents?: true

Size: 1.73 KB

Versions: 1

Compression:

Stored size: 1.73 KB

Contents

#!/usr/bin/env ruby
require 'uri'
require 'csv'
require 'slop'
require 'json'
require 'open-uri'

def strict_value(str,default)
  return default unless str
  return default if str.is_a? String and str.size<=0
  str
end

define_method :fmt_json do |main_hash,*args|
  puts main_hash.to_json
end

define_method :fmt_csv do |main_hash,separator|
  puts main_hash.values.map{|tmp| next tmp.join(separator) if tmp.is_a? Array;tmp}.to_csv
end

define_method :fmt_raw do |main_hash,*args|
  puts main_hash[:entity], ''
  if main_hash[:entity].ascii_only?
    puts "US[#{main_hash[:phonetic_us]}]"
    puts "UK[#{main_hash[:phonetic_uk]}]"
  else
    puts "Phonetic[#{main_hash[:phonetic]}]"
  end
  puts '' 
  puts main_hash[:translation]
end

begin
  opts = Slop.parse do |o|
    o.string *%w{-f --format}, 'available choices: json,csv,raw(default)', default: 'raw'
    o.string *%w{-s --separator},'separator used in array#join in csv format(default: NEWLINE)',default: "\n"
  end
rescue Slop::MissingArgument
  puts 'Missing arguments!'
rescue Slop::UnknownOption
  puts 'Unknown options!'
end


if opts
  entity = opts.args.first
  if entity
    tmp_hash = JSON.parse(open("http://dict.youdao.com/jsonresult?q=#{URI.encode(entity)}&type=1").read)
    main_hash = { entity: entity }
    if entity.ascii_only?
      main_hash[:phonetic_us]=strict_value(tmp_hash['sm'],'No US Phonetic')
      main_hash[:phonetic_uk]=strict_value(tmp_hash['uksm'],'No UK Phonetic')
    else
      main_hash[:phonetic]=strict_value(tmp_hash['sm'],'No Phonetic')
    end
    main_hash[:translation]=strict_value(tmp_hash['basic'],'No Translation')
    send "fmt_#{opts[:format]}", main_hash,opts[:separator]
  else
    puts 'Missing target, please specify a word or phrase!'
    exit
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
arb-dict-0.2.0 bin/arb-dict