Lingara Lingara 說明文件 學習指南 API 函式庫 App 建立 網頁版
語言: 繁體中文

Ruby

本頁譯自英文。如兩者有出入,以英文頁面為準。 閱讀英文頁面

Ruby 函式庫是 RubyGems 上的 lingara gem。它需要 Ruby 3.3 或更新版本,使用標準函式庫中的 Net::HTTP,不依賴任何其他 gem。

使用方式

  • 呼叫是同步的。一個用戶端可以在多個執行緒之間共用,而且在 fork 之後依然正確。
  • 傳一個區塊給串流呼叫,每個事件都會逐一交給它。不傳區塊時,你會得到一個 Enumerable 串流,它是惰性的:請求會在第一次 each 或 next 時才送出。用 next 讀取的串流需要明確呼叫 close。
  • 用 case 和 in 比對事件。
  • 要提早停止串流,可以用 break 離開區塊,或是呼叫 close。
  • 錯誤繼承自 Lingara::Error。retry_after 是秒數,當 API 沒有指定等待時間時為 nil。
  • 以關鍵字引數呼叫 Lingara::Client.new 來建立用戶端。Net::HTTP 的選項放在 net_http_options 中;它的讀取逾時同時也是串流的閒置逾時。

下面的範例會安裝 gem、建立用戶端、以串流方式取得詞彙清單並處理錯誤。

Ruby

gem install lingara -v 0.1.0-alpha.6

Ruby

require "lingara"

client = Lingara::Client.new(client_id: client_id, client_secret: client_secret)

Ruby

client.generate_vocabulary(level: 2, source_lang: "en", target_lang: "zh", count: 8) do |event|
  case event
  in Lingara::GenerateVocabularyEventItem => item then puts "#{item.data.word}: #{item.data.translation}"
  else nil
  end
end

Ruby

begin
  client.get_usage
rescue Lingara::ApiError => e
  # A refusal from the API: status, code (stable) and message (localised).
  puts "#{e.status} #{e.code}: #{e.message}"
  puts "retry after #{e.retry_after}s" if e.retry_after
rescue Lingara::OAuthError => e
  # The token endpoint refused the credentials or the scopes.
  puts "#{e.status} #{e.error}: #{e.description}"
rescue Lingara::MaintenanceError => e
  puts "under maintenance"
  puts "retry after #{e.retry_after}s" if e.retry_after
rescue Lingara::TransportError => e
  # No usable answer: :connect, :tls, :reset, :timeout, and so on.
  puts "transport: #{e.kind}"
end

本頁封裝的內容