Lingara Lingara Docs Guides API Libraries Apps Build Web app
Language: English

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 Enumerable stream instead, which is lazy: the request is sent on the first each or next. A stream read with next needs an explicit close.
  • Match events with case and in.
  • To stop a stream early, leave the block with break, or call close.
  • Errors inherit from Lingara::Error. retry_after is a number of seconds, or nil when the API named no wait.
  • Create a client with keyword arguments to Lingara::Client.new. Options for Net::HTTP go in net_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.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

What this page wraps