Ruby
The Ruby library is the lingara gem on RubyGems. It needs Ruby 3.3 or later and uses Net::HTTP from the standard library, with no other gems.
How it reads
- Calls are synchronous. One client can be shared between threads, and it stays correct across a
fork. - Pass a block to a streaming call and each event is yielded to it. Without a block you get an
Enumerablestream instead, which is lazy: the request is sent on the firsteachornext. A stream read withnextneeds an explicitclose. - Match events with
caseandin. - To stop a stream early, leave the block with
break, or callclose. - Errors inherit from
Lingara::Error.retry_afteris a number of seconds, ornilwhen the API named no wait. - Create a client with keyword arguments to
Lingara::Client.new. Options for Net::HTTP go innet_http_options; its read timeout is also the stream’s idle timeout.
The samples below install the gem, create a client, stream a vocabulary list and handle an error.
Ruby
gem install lingara -v 0.1.0-alpha.6Ruby
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
endRuby
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