Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

first release

  • Loading branch information...
commit 27ea18b8fa436e10dd08a99f12e0d4947de1aa95 1 parent f91e6a2
@vkill authored
Showing with 1,313 additions and 6 deletions.
  1. +8 −0 .gitignore
  2. +4 −0 CHANGELOG
  3. +42 −6 README.markdown
  4. +48 −0 bin/youdao_fanyi
  5. +170 −0 examples/translate.rb
  6. +2 −0  lib/generators/youdao_fanyi/install/USAGE
  7. +14 −0 lib/generators/youdao_fanyi/install/install_generator.rb
  8. +7 −0 lib/generators/youdao_fanyi/install/templates/youdao_fanyi.rb
  9. +9 −0 lib/generators/youdao_fanyi/install/templates/youdao_fanyi_api_keys.yml
  10. +32 −0 lib/youdao_fanyi.rb
  11. +14 −0 lib/youdao_fanyi/configuration.rb
  12. +42 −0 lib/youdao_fanyi/connector.rb
  13. +15 −0 lib/youdao_fanyi/errors.rb
  14. +43 −0 lib/youdao_fanyi/translator.rb
  15. +2 −0  lib/youdao_fanyi/version.rb
  16. +4 −0 spec/rails3_0_app/.gitignore
  17. +7 −0 spec/rails3_0_app/Gemfile
  18. +7 −0 spec/rails3_0_app/Rakefile
  19. +3 −0  spec/rails3_0_app/app/controllers/application_controller.rb
  20. +2 −0  spec/rails3_0_app/app/helpers/application_helper.rb
  21. +14 −0 spec/rails3_0_app/app/views/layouts/application.html.erb
  22. +4 −0 spec/rails3_0_app/config.ru
  23. +42 −0 spec/rails3_0_app/config/application.rb
  24. +6 −0 spec/rails3_0_app/config/boot.rb
  25. +22 −0 spec/rails3_0_app/config/database.yml
  26. +5 −0 spec/rails3_0_app/config/environment.rb
  27. +26 −0 spec/rails3_0_app/config/environments/development.rb
  28. +49 −0 spec/rails3_0_app/config/environments/production.rb
  29. +35 −0 spec/rails3_0_app/config/environments/test.rb
  30. +7 −0 spec/rails3_0_app/config/initializers/backtrace_silencers.rb
  31. +10 −0 spec/rails3_0_app/config/initializers/inflections.rb
  32. +5 −0 spec/rails3_0_app/config/initializers/mime_types.rb
  33. +7 −0 spec/rails3_0_app/config/initializers/secret_token.rb
  34. +8 −0 spec/rails3_0_app/config/initializers/session_store.rb
  35. +7 −0 spec/rails3_0_app/config/initializers/youdao_fanyi.rb
  36. +5 −0 spec/rails3_0_app/config/locales/en.yml
  37. +58 −0 spec/rails3_0_app/config/routes.rb
  38. +7 −0 spec/rails3_0_app/db/seeds.rb
  39. 0  spec/rails3_0_app/lib/tasks/.gitkeep
  40. +26 −0 spec/rails3_0_app/public/404.html
  41. +26 −0 spec/rails3_0_app/public/422.html
  42. +26 −0 spec/rails3_0_app/public/500.html
  43. 0  spec/rails3_0_app/public/favicon.ico
  44. BIN  spec/rails3_0_app/public/images/rails.png
  45. +239 −0 spec/rails3_0_app/public/index.html
  46. 0  spec/rails3_0_app/public/javascripts/.gitkeep
  47. 0  spec/rails3_0_app/public/javascripts/application.js
  48. +5 −0 spec/rails3_0_app/public/robots.txt
  49. 0  spec/rails3_0_app/public/stylesheets/.gitkeep
  50. +6 −0 spec/rails3_0_app/script/rails
  51. 0  spec/rails3_0_app/vendor/plugins/.gitkeep
  52. +9 −0 spec/spec_helper.rb
  53. +9 −0 spec/support/youdao_fanyi_api_keys.yml.example
  54. +16 −0 spec/youdao_fanyi/configuration_spec.rb
  55. +86 −0 spec/youdao_fanyi/connector_spec.rb
  56. +39 −0 spec/youdao_fanyi/translator_spec.rb
  57. +28 −0 spec/youdao_fanyi_spec.rb
  58. +6 −0 youdao_fanyi.gemspec
View
8 .gitignore
@@ -15,3 +15,11 @@ spec/reports
test/tmp
test/version_tmp
tmp
+
+spec/rails3_0_app/db/*.sqlite3
+spec/rails3_0_app/log/*
+spec/rails3_0_app/tmp/*
+
+
+spec/support/youdao_fanyi_api_keys.yml
+spec/rails3_0_app/config/youdao_fanyi_api_keys.yml
View
4 CHANGELOG
@@ -0,0 +1,4 @@
+== 0.1.0
+
+* First release
+
View
48 README.markdown
@@ -1,6 +1,6 @@
#YoudaoFanyi
-YoudaoFanyi is a http://fanyi.youdao.com api library for Ruby and Rails3.
+YoudaoFanyi is a http://fanyi.youdao.com api library for Ruby and Rails3. it only support en<=>zh-CN translate.
* https://github.com/vkill/youdao_fanyi
@@ -11,7 +11,30 @@ YoudaoFanyi is a http://fanyi.youdao.com api library for Ruby and Rails3.
* Rails 3.0.x, 3.1
-##Installation
+##Use in Ruby scripts
+
+more see `examples/translate.rb`.
+
+ #encoding: utf-8
+ require "pp"
+ require "youdao_fanyi"
+
+ YoudaoFanyi.configure do |config|
+ config.api_keys = [
+ { "keyfrom" => "blog-vkill-net", "key" => "2022446265" }
+ ]
+ end
+
+ puts YoudaoFanyi.t("china")
+
+ YoudaoFanyi::Translator.translate("china", :i, nil, true, false, "") do |results|
+ p [results.error_code, results.translation, results.query]
+ pp results.results
+ end
+
+##Use in Rails3
+
+###Installation
In your app's `Gemfile`, add:
@@ -22,19 +45,32 @@ Then run:
> bundle
> rails generate youdao_fanyi:install
-Configure your http://fanyi.youdao.com api keys, edit `config/initializers/youdao_fanyi.rb`
+Configure your http://fanyi.youdao.com api keys, edit `config/youdao_fanyi_api_keys.yml`
+Configure use proxy, edit `config/initializers/youdao_fanyi.rb`
-##Uninstallation
+
+###Uninstallation from Rails3
Run:
> rails destroy youdao_fanyi:install
-##Usage Example
+###Usage Examples
+
+basic example in the rails console, more see `examples/translate.rb`.
+
+ > YoudaoFanyi.t(:i) => ["我"]
+ > YoudaoFanyi.t(:i, :china) => ["我", "中国"]
+
+
+When your want translate models attributes, please use https://github.com/vkill/i18n_attributes, it auto use this gem. (WARN: this function wait support!!!)
+
+
+##Use in shell
-When your want translate models attributes, please use [i18n_attributes][https://github.com/vkill/i18n_attributes], it auto use this gem.
+ > # youdao_fanyi --key 2022446265 --keyfrom blog-vkill-net "详细" i you
##Copyright
View
48 bin/youdao_fanyi
@@ -0,0 +1,48 @@
+#!/usr/bin/env ruby
+require "optparse"
+
+require "pp"
+$:.push File.expand_path("../../lib", __FILE__)
+require "youdao_fanyi"
+
+options = {}
+OptionParser.new do |opts|
+ opts.banner = "Usage: youdao_fanyi [--key API_Key] [--keyfrom API_KeyFrom] STRING [STRING, ...]"
+
+ opts.on('--key API_Key', "A 'http://fanyi.youdao.com/fanyiapi?path=data-mode' API key") do |key|
+ options[:key] = key
+ end
+
+ opts.on('--keyfrom API_KeyFrom', "A 'http://fanyi.youdao.com/fanyiapi?path=data-mode' API keyfrom") do |keyfrom|
+ options[:keyfrom] = keyfrom
+ end
+
+ opts.on("-v", "--version", "The current version of YoudaoFanyi") do
+ puts "YoudaoFanyi v#{YoudaoFanyi::VERSION}"
+ exit
+ end
+
+ opts.on("-h", "--help", "This help screen") do
+ puts opts
+ exit
+ end
+
+end.parse!
+
+STDERR.puts "fanyi.youdao.com API key is required" unless options[:key]
+STDERR.puts "fanyi.youdao.com API keyfrom is required" unless options[:keyfrom]
+STDERR.puts "At least one string to translate is required" unless ARGV.size >= 1
+
+YoudaoFanyi.configure do |config|
+ config.api_keys = [
+ { "keyfrom" => options[:keyfrom], "key" => options[:key] }
+ ]
+end
+
+YoudaoFanyi::Translator.translate(*ARGV) do |results|
+# puts results.translation
+ puts "======================================="
+ pp results.results
+ puts "======================================="
+end
+
View
170 examples/translate.rb
@@ -0,0 +1,170 @@
+#encoding: utf-8
+
+require "pp"
+$:.push File.expand_path("../../lib", __FILE__)
+require "youdao_fanyi"
+
+YoudaoFanyi.configure do |config|
+ config.api_keys = [
+ { "keyfrom" => "blog-vkill-net", "key" => "2022446265" }
+ ]
+end
+
+puts YoudaoFanyi.t("china")
+puts "======================================="
+
+YoudaoFanyi::Translator.translate("中国", "china", :i, nil, true, false, "") do |results|
+ p [results.error_code, results.translation, results.query]
+ pp results.results
+ puts "======================================="
+end
+
+
+
+=begin
+
+[root@vkill-arch youdao_fanyi]# ruby examples/translate.rb
+中国
+=======================================
+[0, "China", "中国"]
+{"translation"=>["China"],
+ "basic"=>{"explains"=>["China"]},
+ "query"=>"中国",
+ "errorCode"=>0,
+ "web"=>
+ [{"value"=>["china", "C.h.i.n.a", "cn", "Chung Kuo, Cina"], "key"=>"中国"},
+ {"value"=>["中国"], "key"=>"中國"},
+ {"value"=>["China Daily", "China News", "Dhina Daily", "Chellona Daily"],
+ "key"=>"中国日报"},
+ {"value"=>
+ ["Great Wall, China",
+ "Great all, Chna",
+ "the Great Wall of China",
+ "GreatWallChina"],
+ "key"=>"中国长城"},
+ {"value"=>["China Unicom", "CHU", "WCDMA", "Unicom"], "key"=>"中国联通"},
+ {"value"=>
+ ["Red Cross Society of China",
+ "RCSC",
+ "Red Cro Society of China",
+ "Chinese Red Cross Society"],
+ "key"=>"中国红十字会"},
+ {"value"=>
+ ["Mainland China", "cn", "the Chinese mainland", "China Mainland"],
+ "key"=>"中国大陆"},
+ {"value"=>["Chinaren", "Chinese people", "The Chinese", "Chinese person"],
+ "key"=>"中国人"},
+ {"value"=>
+ ["Chinese Literature", "Chinese play", "CHI.LIT", "Chinese novelist"],
+ "key"=>"中国文学"},
+ {"value"=>["China News", "Chugoku Shimbun", "CCTV NEWS", "News of China"],
+ "key"=>"中国新闻"}]}
+=======================================
+[0, "中国", "china"]
+{"translation"=>["中国"],
+ "basic"=>{"phonetic"=>"'tʃainə", "explains"=>["n. 瓷器", "adj. 瓷制的"]},
+ "query"=>"china",
+ "errorCode"=>0,
+ "web"=>
+ [{"value"=>["中国", "国际集成电路研讨会暨展览会", "安世亚太", "中华"], "key"=>"China"},
+ {"value"=>["中国日报", "中国日报社", "中国日报英文版", "中国报"], "key"=>"China Daily"},
+ {"value"=>["中国移动", "中国移动通信公司", "中国移动通信", "神州移动"], "key"=>"China Mobile"},
+ {"value"=>["周年", "瓷婚", "搪瓷婚", "瓷器婚"], "key"=>"China Wedding"},
+ {"value"=>["月季", "月季花", "中国玫瑰", "扶桑"], "key"=>"China rose"},
+ {"value"=>["中国新闻", "中国日报", "新闻", "中国"], "key"=>"China News"},
+ {"value"=>["中国报道", "中国述评"], "key"=>"China Report"},
+ {"value"=>["中国网通", "神州网通", "中国网通集团", "中国网通集团公司"], "key"=>"China Netcom"},
+ {"value"=>["中国各地", "各地"], "key"=>"Around China"},
+ {"value"=>["美丽中国", "锦绣中华", "野性中国", "纪录片"], "key"=>"Wild China"}]}
+=======================================
+[0, "我", "i"]
+{"translation"=>["我"],
+ "basic"=>{"phonetic"=>"ai", "explains"=>["pron. 我", "n. 碘元素;英语字母I"]},
+ "query"=>"i",
+ "errorCode"=>0,
+ "web"=>
+ [{"value"=>["输入", "保单险", "所得税", "I"], "key"=>"I"},
+ {"value"=>["我明白", "我明白了", "我知道", "知道了"], "key"=>"I see"},
+ {"value"=>["工字梁", "工形梁"], "key"=>"I beam"},
+ {"value"=>["位输入", "输出恢复时间"], "key"=>"bit I"},
+ {"value"=>["有里知花", "我哭泣", "罗百吉", "我哭了"], "key"=>"i cry"},
+ {"value"=>["伊丽莎白一世", "伊莉莎白一世", "伊莉莎白女王", "伊利莎白一世"], "key"=>"Elizabeth I"},
+ {"value"=>["张力尹", "我愿意", "张力尹星愿", "我将要"], "key"=>"I Will"},
+ {"value"=>["学习精要", "模拟试卷及详解考试", "第一级", "考试"], "key"=>"Level I"},
+ {"value"=>["Samsung", "Samsung I8000 Omnia II", "Anycall"], "key"=>"三星I"},
+ {"value"=>["我认为", "我思故我在", "我想", "双子座"], "key"=>"I think"}]}
+=======================================
+[0, "零", "nil"]
+{"translation"=>["零"],
+ "basic"=>{"phonetic"=>"nil", "explains"=>["n. 无,零"]},
+ "query"=>"nil",
+ "errorCode"=>0,
+ "web"=>
+ [{"value"=>["无", "近等基因系", "零点", "尼尔"], "key"=>"nil"},
+ {"value"=>["牵牛花", "大花牵牛"], "key"=>"Pharbitis nil"},
+ {"value"=>["幂零根基"], "key"=>"nil radical"},
+ {"value"=>["零耦合"], "key"=>"Nil Coupling"},
+ {"value"=>["给自己", "给本身", "给本人"], "key"=>"guoL niL"},
+ {"value"=>["非零溶解度"], "key"=>"nil solubility"},
+ {"value"=>["吉理曼"], "key"=>"Nil Guillemette"},
+ {"value"=>["尼尔酒店"], "key"=>"nil hotel"},
+ {"value"=>["硬摇滚"], "key"=>"T nil"},
+ {"value"=>["无货"], "key"=>"Cargo NIL"}]}
+=======================================
+[0, "真正的", "true"]
+{"translation"=>["真正的"],
+ "basic"=>
+ {"phonetic"=>"tru:",
+ "explains"=>["adj. 真实的;正确的", "adv. 真实地;准确地", "n. 真实;准确", "vt. 装准"]},
+ "query"=>"true",
+ "errorCode"=>0,
+ "web"=>
+ [{"value"=>["真", "真实的", "校准", "真正的"], "key"=>"True"},
+ {"value"=>["真爱如血", "噬血真爱", "嗜血真爱", "第一季"], "key"=>"True Blood"},
+ {"value"=>["真地平", "真地平线", "真水平线", "真实水平"], "key"=>"true horizon"},
+ {"value"=>["真正的美", "真实之美", "真善美", "美丽审判"], "key"=>"True Beauty"},
+ {"value"=>["有效", "适用"], "key"=>"hold true"},
+ {"value"=>["真北", "正北", "真实北国", "真实北向"], "key"=>"TRUE NORTH"},
+ {"value"=>["苏乞儿"], "key"=>"True Legend"},
+ {"value"=>["位置度", "真位", "真船位", "真正位置的孔"], "key"=>"true position"},
+ {"value"=>["本来面目", "本色", "真向", "英雄正传"], "key"=>"true colours"},
+ {"value"=>["真实租赁", "正式租赁", "真事租赁"], "key"=>"true lease"}]}
+=======================================
+[0, "假", "false"]
+{"translation"=>["假"],
+ "basic"=>{"phonetic"=>"fɔ:ls", "explains"=>["adj. 错误的;虚伪的;伪造的", "adv. 欺诈地"]},
+ "query"=>"false",
+ "errorCode"=>0,
+ "web"=>
+ [{"value"=>["错误", "假的", "虚假的", "不成立"], "key"=>"False"},
+ {"value"=>["假阴性", "伪阴性", "负误识", "错误否定"], "key"=>"False negative"},
+ {"value"=>["假阳性", "伪阳性", "正误识", "错误肯定"], "key"=>"False positive"},
+ {"value"=>["假市", "虚假市场"], "key"=>"false market"},
+ {"value"=>["假睫毛"], "key"=>"false eyelash"},
+ {"value"=>["骗人的外表", "假面具", "装饰正面", "假锋"], "key"=>"false front"},
+ {"value"=>["一种形式的试题"], "key"=>"false Exam"},
+ {"value"=>["假紫晶"], "key"=>"false amethyst"},
+ {"value"=>["假年轮", "伪年轮"], "key"=>"false ring"},
+ {"value"=>["假天花板", "假平顶", "假顶棚", "假天华板"], "key"=>"false ceiling"}]}
+=======================================
+[0, "零", "nil"]
+{"translation"=>["零"],
+ "basic"=>{"phonetic"=>"nil", "explains"=>["n. 无,零"]},
+ "query"=>"nil",
+ "errorCode"=>0,
+ "web"=>
+ [{"value"=>["无", "近等基因系", "零点", "尼尔"], "key"=>"nil"},
+ {"value"=>["牵牛花", "大花牵牛"], "key"=>"Pharbitis nil"},
+ {"value"=>["幂零根基"], "key"=>"nil radical"},
+ {"value"=>["零耦合"], "key"=>"Nil Coupling"},
+ {"value"=>["给自己", "给本身", "给本人"], "key"=>"guoL niL"},
+ {"value"=>["非零溶解度"], "key"=>"nil solubility"},
+ {"value"=>["吉理曼"], "key"=>"Nil Guillemette"},
+ {"value"=>["尼尔酒店"], "key"=>"nil hotel"},
+ {"value"=>["硬摇滚"], "key"=>"T nil"},
+ {"value"=>["无货"], "key"=>"Cargo NIL"}]}
+=======================================
+
+
+=end
+
View
2  lib/generators/youdao_fanyi/install/USAGE
@@ -0,0 +1,2 @@
+Description:
+
View
14 lib/generators/youdao_fanyi/install/install_generator.rb
@@ -0,0 +1,14 @@
+class YoudaoFanyi::InstallGenerator < Rails::Generators::Base
+ source_root File.expand_path('../templates', __FILE__)
+
+ def create_yml_file
+ template "youdao_fanyi_api_keys.yml", 'config/youdao_fanyi_api_keys.yml'
+ end
+
+ def create_initializer_file
+ template "youdao_fanyi.rb", 'config/initializers/youdao_fanyi.rb'
+ end
+
+
+end
+
View
7 lib/generators/youdao_fanyi/install/templates/youdao_fanyi.rb
@@ -0,0 +1,7 @@
+if Rails.env.development?
+ YoudaoFanyi.configure do |config|
+ config.api_keys = YAML.load_file(Rails.root.join("config/youdao_fanyi_api_keys.yml").to_s)["youdao_fanyi_api_keys"]
+# config.http_proxy = 'http://127.0.0.1:8118'
+ end
+end
+
View
9 lib/generators/youdao_fanyi/install/templates/youdao_fanyi_api_keys.yml
@@ -0,0 +1,9 @@
+# key,keyfrom please see http://fanyi.youdao.com/fanyiapi?path=data-mode
+
+youdao_fanyi_api_keys:
+ - keyfrom: blog-vkill-net
+ key: 2022446265
+ # if your only use one key&keyfrom, please destroy the following code.
+ - keyfrom: keyfrom2
+ key: key2
+
View
32 lib/youdao_fanyi.rb
@@ -1,5 +1,37 @@
+#encoding: utf-8
+$KCODE = 'u' unless RUBY_VERSION >= "1.9"
+
require "youdao_fanyi/version"
+require "active_support/core_ext/object"
+require "yaml"
+require "httparty"
+require "json"
+require "uri"
+#require "cgi"
+
+require "youdao_fanyi/errors"
+require "youdao_fanyi/configuration"
+require "youdao_fanyi/connector"
+require "youdao_fanyi/translator"
+
module YoudaoFanyi
+ def self.configure
+ yield Configuration
+ reload!
+ end
+
+ def self.reload!
+ load "youdao_fanyi/connector.rb"
+ load "youdao_fanyi/translator.rb"
+ end
+
+ def self.api_key
+ YoudaoFanyi::Configuration.api_keys.sort_by!{rand()}.first
+ end
+
+ def self.t(*words)
+ YoudaoFanyi::Translator.t(*words)
+ end
end
View
14 lib/youdao_fanyi/configuration.rb
@@ -0,0 +1,14 @@
+#encoding: utf-8
+
+# YoudaoFanyi::Configuration.http_proxy = 'http://127.0.0.1:8118'
+
+module YoudaoFanyi
+ Configuration = Struct.new(
+ :api_keys,
+ :http_proxy
+ ).new(
+ [{ "keyfrom" => "test.vkill.net", "key" => "1234567890" }],
+ nil
+ )
+end
+
View
42 lib/youdao_fanyi/connector.rb
@@ -0,0 +1,42 @@
+#encoding: utf-8
+
+module YoudaoFanyi
+ class Connector
+
+ attr_accessor :key, :keyfrom
+ attr_reader :q, :results, :response, :error_code, :translation, :query
+
+ include HTTParty
+
+ base_uri 'http://fanyi.youdao.com/fanyiapi.do'
+ default_params :type => :data, :doctype => :json, :version => 1.1
+
+ # YoudaoFanyi::Configuration.http_proxy = 'http://127.0.0.1:8118'
+ #or
+ # > export http_proxy=http://localhost:8118
+ if proxy = YoudaoFanyi::Configuration.http_proxy || ENV['http_proxy']
+ proxy = URI.parse(proxy)
+ http_proxy proxy.host, proxy.port
+ end
+
+ def initialize
+ api_key = YoudaoFanyi.api_key()
+ @key = api_key["key"] || api_key[:key]
+ @keyfrom = api_key["keyfrom"] || api_key[:keyfrom]
+ end
+
+ def request(word, *options)
+ options = options.extract_options!
+ @q = word.to_s
+ @response = self.class.get('', :query => {:q => word}.merge(:key => @key, :keyfrom => @keyfrom))
+# require "pry"
+# binding.pry
+ @results = JSON.load(@response.body)
+ @error_code, @query = @results['errorCode'], @results['query']
+ @translation = @error_code == 0 ? @results['translation'].first : YoudaoFanyi::Errors.error_message(@error_code)
+ self
+ end
+
+ end
+end
+
View
15 lib/youdao_fanyi/errors.rb
@@ -0,0 +1,15 @@
+#encoding: utf-8
+
+module YoudaoFanyi
+ module Errors
+ def self.error_message(error_code)
+ "ERROR:" + case error_code.to_i
+ when 50
+ "key or keyfrom error!"
+ else
+ "unknow error!"
+ end
+ end
+ end
+end
+
View
43 lib/youdao_fanyi/translator.rb
@@ -0,0 +1,43 @@
+#encoding: utf-8
+
+module YoudaoFanyi
+ class Translator
+ attr_reader :queries
+
+ def initialize(*options)
+ options.extract_options!.each {|k,v| instance_variable_set :"@#{k.to_s}", v}
+ end
+
+ def self.translate(*words, &block)
+ options = words.extract_options!
+ not_translate = options.delete(:not_translate) || false
+ words = format_words(words)
+ if not_translate
+ self.new(:queries => words)
+ else
+ words.map do |word|
+ connector = YoudaoFanyi::Connector.new.request(word)
+ block ? (yield connector) : connector
+ end
+ end
+ end
+
+ def self.t(*words)
+ translate(*words) {|connector| connector.translation}
+ end
+
+ private
+ def self.format_words(words)
+ words.map do |word|
+ case word
+ when nil, ""
+ 'nil'
+ else
+ word.to_s
+ end
+ end.keep_if {|x| !x.to_s.empty?}
+ end
+
+ end
+end
+
View
2  lib/youdao_fanyi/version.rb
@@ -1,3 +1,5 @@
+#encoding: utf-8
+
module YoudaoFanyi
VERSION = "0.1.0"
end
View
4 spec/rails3_0_app/.gitignore
@@ -0,0 +1,4 @@
+.bundle
+db/*.sqlite3
+log/*.log
+tmp/
View
7 spec/rails3_0_app/Gemfile
@@ -0,0 +1,7 @@
+source 'http://rubygems.org'
+
+gem 'rails', '3.0.11'
+gem 'sqlite3-ruby', :require => 'sqlite3'
+
+gem "youdao_fanyi", :path => '../../'
+
View
7 spec/rails3_0_app/Rakefile
@@ -0,0 +1,7 @@
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+require 'rake'
+
+Rails30App::Application.load_tasks
View
3  spec/rails3_0_app/app/controllers/application_controller.rb
@@ -0,0 +1,3 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+end
View
2  spec/rails3_0_app/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
View
14 spec/rails3_0_app/app/views/layouts/application.html.erb
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Rails30App</title>
+ <%= stylesheet_link_tag :all %>
+ <%= javascript_include_tag :defaults %>
+ <%= csrf_meta_tag %>
+</head>
+<body>
+
+<%= yield %>
+
+</body>
+</html>
View
4 spec/rails3_0_app/config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run Rails30App::Application
View
42 spec/rails3_0_app/config/application.rb
@@ -0,0 +1,42 @@
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+# If you have a Gemfile, require the gems listed there, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env) if defined?(Bundler)
+
+module Rails30App
+ class Application < Rails::Application
+ # Settings in config/environments/* take precedence over those specified here.
+ # Application configuration should go into files in config/initializers
+ # -- all .rb files in that directory are automatically loaded.
+
+ # Custom directories with classes and modules you want to be autoloadable.
+ # config.autoload_paths += %W(#{config.root}/extras)
+
+ # Only load the plugins named here, in the order given (default is alphabetical).
+ # :all can be used as a placeholder for all plugins not explicitly named.
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
+
+ # Activate observers that should always be running.
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
+
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
+ # config.time_zone = 'Central Time (US & Canada)'
+
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
+ # config.i18n.default_locale = :de
+
+ # JavaScript files you want as :defaults (application.js is always included).
+ config.action_view.javascript_expansions[:defaults] = %w()
+
+ # Configure the default encoding used in templates for Ruby 1.9.
+ config.encoding = "utf-8"
+
+ # Configure sensitive parameters which will be filtered from the log file.
+ config.filter_parameters += [:password]
+ end
+end
View
6 spec/rails3_0_app/config/boot.rb
@@ -0,0 +1,6 @@
+require 'rubygems'
+
+# Set up gems listed in the Gemfile.
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
View
22 spec/rails3_0_app/config/database.yml
@@ -0,0 +1,22 @@
+# SQLite version 3.x
+# gem install sqlite3
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
+ timeout: 5000
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: sqlite3
+ database: db/test.sqlite3
+ pool: 5
+ timeout: 5000
+
+production:
+ adapter: sqlite3
+ database: db/production.sqlite3
+ pool: 5
+ timeout: 5000
View
5 spec/rails3_0_app/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+Rails30App::Application.initialize!
View
26 spec/rails3_0_app/config/environments/development.rb
@@ -0,0 +1,26 @@
+Rails30App::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # In the development environment your application's code is reloaded on
+ # every request. This slows down response time but is perfect for development
+ # since you don't have to restart the webserver when you make code changes.
+ config.cache_classes = false
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_view.debug_rjs = true
+ config.action_controller.perform_caching = false
+
+ # Don't care if the mailer can't send
+ config.action_mailer.raise_delivery_errors = false
+
+ # Print deprecation notices to the Rails logger
+ config.active_support.deprecation = :log
+
+ # Only use best-standards-support built into browsers
+ config.action_dispatch.best_standards_support = :builtin
+end
+
View
49 spec/rails3_0_app/config/environments/production.rb
@@ -0,0 +1,49 @@
+Rails30App::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # The production environment is meant for finished, "live" apps.
+ # Code is not reloaded between requests
+ config.cache_classes = true
+
+ # Full error reports are disabled and caching is turned on
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Specifies the header that your server uses for sending files
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
+
+ # For nginx:
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
+
+ # If you have no front-end server that supports something like X-Sendfile,
+ # just comment this out and Rails will serve the files
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Use a different logger for distributed setups
+ # config.logger = SyslogLogger.new
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Disable Rails's static asset server
+ # In production, Apache or nginx will already do this
+ config.serve_static_assets = false
+
+ # Enable serving of images, stylesheets, and javascripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
+ # the I18n.default_locale when a translation can not be found)
+ config.i18n.fallbacks = true
+
+ # Send deprecation notices to registered listeners
+ config.active_support.deprecation = :notify
+end
View
35 spec/rails3_0_app/config/environments/test.rb
@@ -0,0 +1,35 @@
+Rails30App::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # Raise exceptions instead of rendering exception templates
+ config.action_dispatch.show_exceptions = false
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ # config.active_record.schema_format = :sql
+
+ # Print deprecation notices to the stderr
+ config.active_support.deprecation = :stderr
+end
View
7 spec/rails3_0_app/config/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+# Rails.backtrace_cleaner.remove_silencers!
View
10 spec/rails3_0_app/config/initializers/inflections.rb
@@ -0,0 +1,10 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new inflection rules using the following format
+# (all these examples are active by default):
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
View
5 spec/rails3_0_app/config/initializers/mime_types.rb
@@ -0,0 +1,5 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new mime types for use in respond_to blocks:
+# Mime::Type.register "text/richtext", :rtf
+# Mime::Type.register_alias "text/html", :iphone
View
7 spec/rails3_0_app/config/initializers/secret_token.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+Rails30App::Application.config.secret_token = '4cfccb2c6f49876a48894d21885a0ccede0abd6a4666dedf4abc7450e1cba6369b1fb3a5cf47fd5a55739dcf4996ecdce996bbdd5cd32d6c2b0ebb34107371a4'
View
8 spec/rails3_0_app/config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+Rails30App::Application.config.session_store :cookie_store, :key => '_rails3_0_app_session'
+
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rails generate session_migration")
+# Rails30App::Application.config.session_store :active_record_store
View
7 spec/rails3_0_app/config/initializers/youdao_fanyi.rb
@@ -0,0 +1,7 @@
+if Rails.env.development?
+ YoudaoFanyi.configure do |config|
+ config.api_keys = YAML.load_file(Rails.root.join("config/youdao_fanyi_api_keys.yml").to_s)["youdao_fanyi_api_keys"]
+# config.http_proxy = 'http://127.0.0.1:8118'
+ end
+end
+
View
5 spec/rails3_0_app/config/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world"
View
58 spec/rails3_0_app/config/routes.rb
@@ -0,0 +1,58 @@
+Rails30App::Application.routes.draw do
+ # The priority is based upon order of creation:
+ # first created -> highest priority.
+
+ # Sample of regular route:
+ # match 'products/:id' => 'catalog#view'
+ # Keep in mind you can assign values other than :controller and :action
+
+ # Sample of named route:
+ # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
+ # This route can be invoked with purchase_url(:id => product.id)
+
+ # Sample resource route (maps HTTP verbs to controller actions automatically):
+ # resources :products
+
+ # Sample resource route with options:
+ # resources :products do
+ # member do
+ # get 'short'
+ # post 'toggle'
+ # end
+ #
+ # collection do
+ # get 'sold'
+ # end
+ # end
+
+ # Sample resource route with sub-resources:
+ # resources :products do
+ # resources :comments, :sales
+ # resource :seller
+ # end
+
+ # Sample resource route with more complex sub-resources
+ # resources :products do
+ # resources :comments
+ # resources :sales do
+ # get 'recent', :on => :collection
+ # end
+ # end
+
+ # Sample resource route within a namespace:
+ # namespace :admin do
+ # # Directs /admin/products/* to Admin::ProductsController
+ # # (app/controllers/admin/products_controller.rb)
+ # resources :products
+ # end
+
+ # You can have the root of your site routed with "root"
+ # just remember to delete public/index.html.
+ # root :to => "welcome#index"
+
+ # See how all your routes lay out with "rake routes"
+
+ # This is a legacy wild controller route that's not recommended for RESTful applications.
+ # Note: This route will make all actions in every controller accessible via GET requests.
+ # match ':controller(/:action(/:id(.:format)))'
+end
View
7 spec/rails3_0_app/db/seeds.rb
@@ -0,0 +1,7 @@
+# This file should contain all the record creation needed to seed the database with its default values.
+# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
+#
+# Examples:
+#
+# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
+# Mayor.create(:name => 'Daley', :city => cities.first)
View
0  spec/rails3_0_app/lib/tasks/.gitkeep
No changes.
View
26 spec/rails3_0_app/public/404.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/404.html -->
+ <div class="dialog">
+ <h1>The page you were looking for doesn't exist.</h1>
+ <p>You may have mistyped the address or the page may have moved.</p>
+ </div>
+</body>
+</html>
View
26 spec/rails3_0_app/public/422.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/422.html -->
+ <div class="dialog">
+ <h1>The change you wanted was rejected.</h1>
+ <p>Maybe you tried to change something you didn't have access to.</p>
+ </div>
+</body>
+</html>
View
26 spec/rails3_0_app/public/500.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ <p>We've been notified about this issue and we'll take a look at it shortly.</p>
+ </div>
+</body>
+</html>
View
0  spec/rails3_0_app/public/favicon.ico
No changes.
View
BIN  spec/rails3_0_app/public/images/rails.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
239 spec/rails3_0_app/public/index.html
@@ -0,0 +1,239 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Ruby on Rails: Welcome aboard</title>
+ <style type="text/css" media="screen">
+ body {
+ margin: 0;
+ margin-bottom: 25px;
+ padding: 0;
+ background-color: #f0f0f0;
+ font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
+ font-size: 13px;
+ color: #333;
+ }
+
+ h1 {
+ font-size: 28px;
+ color: #000;
+ }
+
+ a {color: #03c}
+ a:hover {
+ background-color: #03c;
+ color: white;
+ text-decoration: none;
+ }
+
+
+ #page {
+ background-color: #f0f0f0;
+ width: 750px;
+ margin: 0;
+ margin-left: auto;
+ margin-right: auto;
+ }
+
+ #content {
+ float: left;
+ background-color: white;
+ border: 3px solid #aaa;
+ border-top: none;
+ padding: 25px;
+ width: 500px;
+ }
+
+ #sidebar {
+ float: right;
+ width: 175px;
+ }
+
+ #footer {
+ clear: both;
+ }
+
+
+ #header, #about, #getting-started {
+ padding-left: 75px;
+ padding-right: 30px;
+ }
+
+
+ #header {
+ background-image: url("images/rails.png");
+ background-repeat: no-repeat;
+ background-position: top left;
+ height: 64px;
+ }
+ #header h1, #header h2 {margin: 0}
+ #header h2 {
+ color: #888;
+ font-weight: normal;
+ font-size: 16px;
+ }
+
+
+ #about h3 {
+ margin: 0;
+ margin-bottom: 10px;
+ font-size: 14px;
+ }
+
+ #about-content {
+ background-color: #ffd;
+ border: 1px solid #fc0;
+ margin-left: -55px;
+ margin-right: -10px;
+ }
+ #about-content table {
+ margin-top: 10px;
+ margin-bottom: 10px;
+ font-size: 11px;
+ border-collapse: collapse;
+ }
+ #about-content td {
+ padding: 10px;
+ padding-top: 3px;
+ padding-bottom: 3px;
+ }
+ #about-content td.name {color: #555}
+ #about-content td.value {color: #000}
+
+ #about-content ul {
+ padding: 0;
+ list-style-type: none;
+ }
+
+ #about-content.failure {
+ background-color: #fcc;
+ border: 1px solid #f00;
+ }
+ #about-content.failure p {
+ margin: 0;
+ padding: 10px;
+ }
+
+
+ #getting-started {
+ border-top: 1px solid #ccc;
+ margin-top: 25px;
+ padding-top: 15px;
+ }
+ #getting-started h1 {
+ margin: 0;
+ font-size: 20px;
+ }
+ #getting-started h2 {
+ margin: 0;
+ font-size: 14px;
+ font-weight: normal;
+ color: #333;
+ margin-bottom: 25px;
+ }
+ #getting-started ol {
+ margin-left: 0;
+ padding-left: 0;
+ }
+ #getting-started li {
+ font-size: 18px;
+ color: #888;
+ margin-bottom: 25px;
+ }
+ #getting-started li h2 {
+ margin: 0;
+ font-weight: normal;
+ font-size: 18px;
+ color: #333;
+ }
+ #getting-started li p {
+ color: #555;
+ font-size: 13px;
+ }
+
+
+ #sidebar ul {
+ margin-left: 0;
+ padding-left: 0;
+ }
+ #sidebar ul h3 {
+ margin-top: 25px;
+ font-size: 16px;
+ padding-bottom: 10px;
+ border-bottom: 1px solid #ccc;
+ }
+ #sidebar li {
+ list-style-type: none;
+ }
+ #sidebar ul.links li {
+ margin-bottom: 5px;
+ }
+
+ </style>
+ <script type="text/javascript">
+ function about() {
+ info = document.getElementById('about-content');
+ if (window.XMLHttpRequest)
+ { xhr = new XMLHttpRequest(); }
+ else
+ { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
+ xhr.open("GET","rails/info/properties",false);
+ xhr.send("");
+ info.innerHTML = xhr.responseText;
+ info.style.display = 'block'
+ }
+ </script>
+ </head>
+ <body>
+ <div id="page">
+ <div id="sidebar">
+ <ul id="sidebar-items">
+ <li>
+ <h3>Browse the documentation</h3>
+ <ul class="links">
+ <li><a href="http://api.rubyonrails.org/">Rails API</a></li>
+ <li><a href="http://stdlib.rubyonrails.org/">Ruby standard library</a></li>
+ <li><a href="http://corelib.rubyonrails.org/">Ruby core</a></li>
+ <li><a href="http://guides.rubyonrails.org/">Rails Guides</a></li>
+ </ul>
+ </li>
+ </ul>
+ </div>
+
+ <div id="content">
+ <div id="header">
+ <h1>Welcome aboard</h1>
+ <h2>You&rsquo;re riding Ruby on Rails!</h2>
+ </div>
+
+ <div id="about">
+ <h3><a href="rails/info/properties" onclick="about(); return false">About your application&rsquo;s environment</a></h3>
+ <div id="about-content" style="display: none"></div>
+ </div>
+
+ <div id="getting-started">
+ <h1>Getting started</h1>
+ <h2>Here&rsquo;s how to get rolling:</h2>
+
+ <ol>
+ <li>
+ <h2>Use <code>rails generate</code> to create your models and controllers</h2>
+ <p>To see all available options, run it without parameters.</p>
+ </li>
+
+ <li>
+ <h2>Set up a default route and remove or rename this file</h2>
+ <p>Routes are set up in config/routes.rb.</p>
+ </li>
+
+ <li>
+ <h2>Create your database</h2>
+ <p>Run <code>rake db:migrate</code> to create your database. If you're not using SQLite (the default), edit <code>config/database.yml</code> with your username and password.</p>
+ </li>
+ </ol>
+ </div>
+ </div>
+
+ <div id="footer">&nbsp;</div>
+ </div>
+ </body>
+</html>
View
0  spec/rails3_0_app/public/javascripts/.gitkeep
No changes.
View
0  spec/rails3_0_app/public/javascripts/application.js
No changes.
View
5 spec/rails3_0_app/public/robots.txt
@@ -0,0 +1,5 @@
+# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file
+#
+# To ban all spiders from the entire site uncomment the next two lines:
+# User-Agent: *
+# Disallow: /
View
0  spec/rails3_0_app/public/stylesheets/.gitkeep
No changes.
View
6 spec/rails3_0_app/script/rails
@@ -0,0 +1,6 @@
+#!/usr/bin/env ruby
+# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
+
+APP_PATH = File.expand_path('../../config/application', __FILE__)
+require File.expand_path('../../config/boot', __FILE__)
+require 'rails/commands'
View
0  spec/rails3_0_app/vendor/plugins/.gitkeep
No changes.
View
9 spec/spec_helper.rb
@@ -3,5 +3,14 @@
require "bundler/setup"
require "pry"
+#loading rspec
+Dir[File.expand_path("../support/**/*.rb", __FILE__)].each {|f| require f}
+RSpec.configure do |config|
+end
+
require "youdao_fanyi"
+YOUDAO_FANYI_API_KEYS = YAML.load_file(
+ File.expand_path("../support/youdao_fanyi_api_keys.yml", __FILE__)
+ )["youdao_fanyi_api_keys"]
+
View
9 spec/support/youdao_fanyi_api_keys.yml.example
@@ -0,0 +1,9 @@
+# key,keyfrom please see http://fanyi.youdao.com/fanyiapi?path=data-mode
+
+youdao_fanyi_api_keys:
+ - keyfrom: blog-vkill-net
+ key: 2022446265
+ # if your only use one key&keyfrom, please destroy the following code.
+ - keyfrom: keyfrom2
+ key: key2
+
View
16 spec/youdao_fanyi/configuration_spec.rb
@@ -0,0 +1,16 @@
+#encoding: utf-8
+require "spec_helper"
+
+describe YoudaoFanyi::Configuration do
+
+ let(:default_configuration) { [{ "keyfrom" => "test.vkill.net", "key" => "1234567890" }] }
+
+ it "default configuration should defined" do
+ YoudaoFanyi::Configuration.api_keys.should == default_configuration
+
+ YoudaoFanyi::Configuration.http_proxy.should == nil
+ end
+
+
+end
+
View
86 spec/youdao_fanyi/connector_spec.rb
@@ -0,0 +1,86 @@
+#encoding: utf-8
+require "spec_helper"
+
+describe YoudaoFanyi::Connector do
+
+ before {
+ YoudaoFanyi::Configuration.api_keys = YOUDAO_FANYI_API_KEYS
+ YoudaoFanyi.reload!
+ }
+
+ let(:base_uri) { 'http://fanyi.youdao.com/fanyiapi.do' }
+ let(:default_params) { {:type => :data, :doctype => :json, :version => 1.1 } }
+
+ def translate(response, query, translation)
+ results = JSON.load(response.body)
+ results["errorCode"].to_i.should == 0
+ results["query"].should == query.to_s
+ results["translation"].include?(translation.to_s).should be_true
+ end
+
+ it "should included HTTParty" do
+ YoudaoFanyi::Connector.include?(HTTParty).should be_true
+ end
+
+ it "base_uri should defined" do
+ YoudaoFanyi::Connector.default_options[:base_uri].should == base_uri
+ end
+
+ it "default_params should defined" do
+ YoudaoFanyi::Connector.default_params[:type].should == default_params[:type]
+ YoudaoFanyi::Connector.default_params[:doctype].should == default_params[:doctype]
+ YoudaoFanyi::Connector.default_params[:version].should == default_params[:version]
+ end
+
+ it "use proxy" do
+ YoudaoFanyi::Configuration.http_proxy = 'http://127.0.0.1:8118'
+ YoudaoFanyi.reload!
+ YoudaoFanyi::Connector.default_options[:http_proxyaddr] = '127.0.0.1'
+ YoudaoFanyi::Connector.default_options[:http_proxyport] = '8118'
+ YoudaoFanyi::Configuration.http_proxy = ''
+ YoudaoFanyi.reload!
+ #ENV['http_proxy']
+ end
+
+ it "translate china should return 中国 by class method" do
+ response = YoudaoFanyi::Connector.get(
+ '', :query => {:q => :china}.merge(YoudaoFanyi.api_key())
+ )
+ translate(response, :china, "中国")
+ end
+
+ it "when initialize, @key and @keyfrom should defined" do
+ connector = YoudaoFanyi::Connector.new
+ connector.key.to_s.empty?.should be_false
+ connector.keyfrom.to_s.empty?.should be_false
+ end
+
+ it "translate china should return 中国 by instance method" do
+ connector = YoudaoFanyi::Connector.new
+ response = connector.class.get(
+ '', :query => {:q => :china}.merge(:key => connector.key, :keyfrom => connector.keyfrom)
+ )
+ translate(response, :china, "中国")
+ end
+
+ it "use translate function" do
+ connector = YoudaoFanyi::Connector.new.request(:china)
+ if connector.error_code == 0
+ connector.translation.should == "中国"
+ else
+ connector.translation.should_not == "中国"
+ connector.translation.should match(/^ERROR:/i)
+ end
+ connector.response.should_not be_nil
+ connector.results.should_not be_nil
+ end
+
+ it "translate function should escape string" do
+ connector = YoudaoFanyi::Connector.new.request(:china)
+ connector.q.should == "china"
+ connector = YoudaoFanyi::Connector.new.request("中国")
+# connector.q.should == "%E4%B8%AD%E5%9B%BD" #CGI::escape
+ connector.q.should == "中国"
+ end
+end
+
View
39 spec/youdao_fanyi/translator_spec.rb
@@ -0,0 +1,39 @@
+#encoding: utf-8
+require "spec_helper"
+
+describe YoudaoFanyi::Translator do
+
+ before {
+ YoudaoFanyi::Configuration.api_keys = YOUDAO_FANYI_API_KEYS
+ YoudaoFanyi.reload!
+ }
+
+ it "should has translate" do
+ YoudaoFanyi::Translator.should respond_to(:translate)
+ end
+
+ it "translate return a instance of YoudaoFanyi::Connector" do
+ YoudaoFanyi::Translator.translate(:china).first.should be_instance_of(YoudaoFanyi::Connector)
+ end
+
+ it "!translate return a instance of self" do
+ YoudaoFanyi::Translator.translate(:china, :not_translate => true).should be_instance_of(YoudaoFanyi::Translator)
+ end
+
+ it "translate special word" do
+ translator = YoudaoFanyi::Translator.translate(nil, true, false, "", :not_translate => true)
+ translator.queries.should == ['nil', 'true', 'false', 'nil']
+ end
+
+ it "should has t" do
+ YoudaoFanyi::Translator.should respond_to(:t)
+ end
+
+ it "only return translation when use t()" do
+ YoudaoFanyi::Translator.t(:china).should == ["中国"]
+ YoudaoFanyi::Translator.t(:china, :i).should == ["中国", ""]
+ end
+
+
+end
+
View
28 spec/youdao_fanyi_spec.rb
@@ -0,0 +1,28 @@
+#encoding: utf-8
+require "spec_helper"
+
+describe YoudaoFanyi do
+ it "should has reload!" do
+ YoudaoFanyi.should respond_to(:reload!)
+ end
+
+ it "should has api_key" do
+ YoudaoFanyi.should respond_to(:api_key)
+ end
+
+ it "should fast define api_keys and rand use api_key from api_keys" do
+ YoudaoFanyi.configure do |config|
+ config.api_keys = YOUDAO_FANYI_API_KEYS
+ end
+ YoudaoFanyi::Configuration.api_keys.should include(YoudaoFanyi.api_key())
+ end
+
+ it "should has t" do
+ YoudaoFanyi.should respond_to(:t)
+ end
+
+ it "t alias YoudaoFanyi::Translator.t" do
+ YoudaoFanyi.t(:china).should == ["中国"]
+ end
+end
+
View
6 youdao_fanyi.gemspec
@@ -20,7 +20,13 @@ Gem::Specification.new do |gem|
gem.add_development_dependency "rspec"
gem.add_development_dependency "guard-rspec"
gem.add_development_dependency "pry"
+ gem.add_development_dependency "rspec-rails"
+
+ #use in spec/rails3_0_app
+ gem.add_development_dependency "rails", "~> 3.0"
+ gem.add_development_dependency "sqlite3-ruby"
gem.add_dependency "httparty", "~> 0.8.1"
+ gem.add_dependency "activesupport", "~> 3.0"
end
Please sign in to comment.
Something went wrong with that request. Please try again.