久しぶりにruby

前に作った辞書検索用のものをまとめてみました。
昔よりキレイに書けるようになった気がする。

その時に気づいたこと*1

  • evalを使えばdispatchが簡単に書ける
  • 継承は結構便利
  • (他にもまだあったかもしれない)

使い方

こんな感じです

#weblioで検索
$ dic_search -w weblio 検索 テスト

コードはこんな感じです><

#!/usr/bin/env ruby
#filename = "dic_search.rb"
=begin
新しい検索用の処理を追加するにはCallerを継承したクラスを作っていく
そのクラスで検索用のurlを作成する処理を定義
	(create_urlを使って@contentにurlを格納)
=end
class Caller
  def initialize
    useja if self.respond_to? :useja
    raise "create_url method is not found." unless self.respond_to? :create_url
  end
  
  def get_meaning word
    @content = create_url word
    #puts "@content is #{@content}"
    system("firefox --new-tab #{@content}")
  end

  alias run get_meaning
end

module Useja
  def useja
      $KCODE="utf8"
      require "uri"
      require "kconv"
  end
end

class EtoJ < Caller
  #和英辞書
  def create_url x
    url=%w{http://dic.livedoor.com/search/?q= &match=startwith&x=0&y=0&dic=ej}
    url.join(x)
  end
end

class EtoE < Caller
  #英英辞書
  def create_url x
    url = "http://pewebdic2.cw.idm.fr/display/display.html?search_str="
    url + x
  end
end

class JtoJ < Caller
  include Useja
  #国語辞書 (gooはeucみたい)
  def create_url x
    url = %w{ http://dictionary.goo.ne.jp/search.php?MT= &kind=jn&mode=0&kwassist=0}
    x = URI.escape(x.toeuc)
    url.join(x)
  end
end

class Weblio < Caller
  include Useja
  def create_url x
    url= "http://www.weblio.jp/content/"
    x = URI.escape(x.toutf8)
    url + x
  end
end

require 'optparse'
dic = nil
ARGV.options do |opt|
  opt.on('-j', '--japanese', '日本語辞書(goo)'){ dic = "JtoJ.new" }
  opt.on('-ej', '--entoja', "英和辞書(livedoor)"){ dic = "EtoJ.new" }
  opt.on('-e', '--english', "英英辞書"){ dic = "EtoE.new"}
  opt.on('-w', '--weblio', "weblioで検索"){ dic = "Weblio.new"}
  opt.parse!
end

if  dic.nil?
  puts "few argument"
  #本当はここでhelpを表示したい><
  exit
end

#eval(dic).d.run(ARGV[0])

a = ARGV.map{ |e| e.split(" ")}.flatten
a.inject(eval(dic)){ |d, e| d.run(e); sleep(0.1); d}

あとでしらべる

対応する引数がなかった時に、helpを表示する方法。
サーバーに負担を掛けない程度のアクセス量
(一つの言葉を検索した後にどれくらい待った方がいいんだろ?)

*1:後で詳しく書くかもしれない