Skip to content

lingodotdev/sdk-ruby

Repository files navigation

Lingo.dev Ruby SDK

A Ruby SDK for integrating with the Lingo.dev localization and translation API. Localize text, objects, and chat messages with support for batch operations, progress tracking, and concurrent processing.

Overview

The Lingo.dev Ruby SDK provides a simple and powerful interface for localizing content in your Ruby applications. It supports:

  • Text, object (Hash), and chat message localization
  • Batch operations for multiple locales or objects
  • Automatic locale recognition
  • Progress tracking with callbacks
  • Concurrent processing for improved performance
  • Comprehensive error handling and validation

Installation

Add this line to your application's Gemfile:

gem'lingodotdev'

And then execute:

bundle install

Or install it yourself with:

gem install lingodotdev

Quick start

require'lingodotdev'# Create an engine instanceengine=LingoDotDev::Engine.new(api_key: 'your-api-key')# Localize textresult=engine.localize_text('Hello world',target_locale: 'es')putsresult# => "Hola mundo"

Usage

Basic text localization

Localize a simple string to a target locale:

engine=LingoDotDev::Engine.new(api_key: 'your-api-key')result=engine.localize_text('Hello world',target_locale: 'es')# => "Hola mundo"# With source locale specifiedresult=engine.localize_text('Hello world',target_locale: 'fr',source_locale: 'en')# => "Bonjour le monde"# Fast mode for quicker resultsresult=engine.localize_text('Hello world',target_locale: 'de',fast: true)# => "Hallo Welt"

Object localization

Localize all string values in a Hash:

data={greeting: 'Hello',farewell: 'Goodbye',message: 'Welcome to our app'}result=engine.localize_object(data,target_locale: 'es')# =>{# greeting: "Hola",# farewell: "Adiós",# message: "Bienvenido a nuestra aplicación"# }

Chat message localization

Localize chat conversations while preserving structure:

chat=[{name: 'user',text: 'Hello!'},{name: 'assistant',text: 'Hi there! How can I help you?'},{name: 'user',text: 'I need some information.'}]result=engine.localize_chat(chat,target_locale: 'ja')# => [#{name: 'user', text: 'こんにちは!' },#{name: 'assistant', text: 'こんにちは!どのようにお手伝いできますか?' },#{name: 'user', text: '情報が必要です。' }# ]

HTML document localization

Localize HTML documents while preserving structure and formatting:

html=<<~HTML<html><head><title>Welcome</title><metaname="description" content="Page description"></head><body><h1>Hello World</h1><p>This is a paragraph with <ahref="/test" title="Link title">a link</a>.</p><imgsrc="/image.jpg" alt="Test image"><inputtype="text" placeholder="Enter text"></body></html>HTMLresult=engine.localize_html(html,target_locale: 'es')# => HTML with localized text content and attributes, lang="es" attribute updated

The method handles:

  • Text content in all elements
  • Localizable attributes: meta content, img alt, input placeholder, a title
  • Preserves HTML structure and formatting
  • Ignores content inside script and style tags
  • Updates the lang attribute on the html element

Batch localization to multiple locales

Localize the same content to multiple target locales:

# Batch localize textresults=engine.batch_localize_text('Hello world',target_locales: ['es','fr','de'])# => ["Hola mundo", "Bonjour le monde", "Hallo Welt"]# With concurrent processing for better performanceresults=engine.batch_localize_text('Hello world',target_locales: ['es','fr','de','ja'],concurrent: true)

Batch localization of multiple objects

Localize multiple objects to the same target locale:

objects=[{title: 'Welcome',body: 'Hello there'},{title: 'About',body: 'Learn more about us'},{title: 'Contact',body: 'Get in touch'}]results=engine.batch_localize_objects(objects,target_locale: 'es',concurrent: true)# => [#{title: "Bienvenido", body: "Hola" },#{title: "Acerca de", body: "Aprende más sobre nosotros" },#{title: "Contacto", body: "Ponte en contacto" }# ]

Locale recognition

Automatically detect the locale of a given text:

locale=engine.recognize_locale('Bonjour le monde')# => "fr"locale=engine.recognize_locale('こんにちは世界')# => "ja"

Progress tracking

Monitor localization progress with callbacks:

# Using a blockresult=engine.localize_text('Hello world',target_locale: 'es')do |progress| puts"Progress: #{progress}%"end# Using the on_progress parametercallback=proc{ |progress| puts"Progress: #{progress}%"}result=engine.localize_text('Hello world',target_locale: 'es',on_progress: callback)

Reference context

Provide additional context to improve translation accuracy:

reference={context: 'greeting',tone: 'formal',domain: 'business'}result=engine.localize_text('Hello',target_locale: 'ja',reference: reference)

Quick translate convenience methods

For one-off translations without managing engine instances:

# Quick translate a stringresult=LingoDotDev::Engine.quick_translate('Hello world',api_key: 'your-api-key',target_locale: 'es')# Quick translate a hashresult=LingoDotDev::Engine.quick_translate({greeting: 'Hello',farewell: 'Goodbye'},api_key: 'your-api-key',target_locale: 'fr')# Quick batch translate to multiple localesresults=LingoDotDev::Engine.quick_batch_translate('Hello',api_key: 'your-api-key',target_locales: ['es','fr','de'])

User information

Check the authenticated user details:

user=engine.whoami# =>{email: "[email protected]", id: "user-id" }

Configuration

The SDK can be configured when creating an engine instance:

engine=LingoDotDev::Engine.new(api_key: 'your-api-key',# Required: Your Lingo.dev API keyapi_url: 'https://engine.lingo.dev',# Optional: API endpoint URLbatch_size: 25,# Optional: Max items per batch (1-250)ideal_batch_item_size: 250# Optional: Target word count per batch (1-2500))

You can also configure using a block:

engine=LingoDotDev::Engine.new(api_key: 'your-api-key')do |config| config.batch_size=50config.ideal_batch_item_size=500end

Configuration options

OptionTypeDefaultDescription
api_keyStringRequiredYour Lingo.dev API key
api_urlStringhttps://engine.lingo.devAPI endpoint URL
batch_sizeInteger25Maximum items per batch (1-250)
ideal_batch_item_sizeInteger250Target word count per batch item (1-2500)

API reference

Instance methods

localize_text(text, target_locale:, source_locale: nil, fast: nil, reference: nil, on_progress: nil, concurrent: false, &block)

Localizes a string to the target locale.

  • Parameters:
    • text (String): Text to localize
    • target_locale (String): Target locale code (e.g., 'es', 'fr', 'ja')
    • source_locale (String, optional): Source locale code
    • fast (Boolean, optional): Enable fast mode
    • reference (Hash, optional): Additional context for translation
    • on_progress (Proc, optional): Progress callback
    • concurrent (Boolean): Enable concurrent processing
    • &block: Alternative progress callback
  • Returns: Localized string

localize_object(obj, target_locale:, source_locale: nil, fast: nil, reference: nil, on_progress: nil, concurrent: false, &block)

Localizes all string values in a Hash.

  • Parameters: Same as localize_text, with obj (Hash) instead of text
  • Returns: Localized Hash

localize_chat(chat, target_locale:, source_locale: nil, fast: nil, reference: nil, on_progress: nil, concurrent: false, &block)

Localizes chat messages. Each message must have :name and :text keys.

  • Parameters: Same as localize_text, with chat (Array) instead of text
  • Returns: Array of localized chat messages

localize_html(html, target_locale:, source_locale: nil, fast: nil, reference: nil, on_progress: nil, concurrent: false, &block)

Localizes an HTML document while preserving structure and formatting. Handles both text content and localizable attributes (alt, title, placeholder, meta content).

  • Parameters:
    • html (String): HTML document string to localize
    • target_locale (String): Target locale code (e.g., 'es', 'fr', 'ja')
    • source_locale (String, optional): Source locale code
    • fast (Boolean, optional): Enable fast mode
    • reference (Hash, optional): Additional context for translation
    • on_progress (Proc, optional): Progress callback
    • concurrent (Boolean): Enable concurrent processing
    • &block: Alternative progress callback
  • Returns: Localized HTML document string with updated lang attribute

batch_localize_text(text, target_locales:, source_locale: nil, fast: nil, reference: nil, concurrent: false)

Localizes text to multiple target locales.

  • Parameters:
    • text (String): Text to localize
    • target_locales (Array): Array of target locale codes
    • Other parameters same as localize_text
  • Returns: Array of localized strings

batch_localize_objects(objects, target_locale:, source_locale: nil, fast: nil, reference: nil, concurrent: false)

Localizes multiple objects to the same target locale.

  • Parameters:
    • objects (Array): Array of Hash objects
    • target_locale (String): Target locale code
    • Other parameters same as localize_object
  • Returns: Array of localized Hash objects

recognize_locale(text)

Detects the locale of the given text.

  • Parameters:
    • text (String): Text to analyze
  • Returns: Locale code string

whoami

Returns information about the authenticated user.

  • Returns: Hash with :email and :id keys, or nil if authentication fails

Class methods

Engine.quick_translate(content, api_key:, target_locale:, source_locale: nil, fast: true, api_url: 'https://engine.lingo.dev')

One-off translation without managing engine lifecycle.

  • Parameters:
    • content (String or Hash): Content to translate
    • Other parameters as in instance methods
  • Returns: Translated String or Hash

Engine.quick_batch_translate(content, api_key:, target_locales:, source_locale: nil, fast: true, api_url: 'https://engine.lingo.dev')

One-off batch translation to multiple locales.

  • Parameters:
    • content (String or Hash): Content to translate
    • target_locales (Array): Array of target locale codes
    • Other parameters as in instance methods
  • Returns: Array of translated results

Error handling

The SDK defines custom exception classes for different error scenarios:

beginengine=LingoDotDev::Engine.new(api_key: 'your-api-key')result=engine.localize_text('Hello',target_locale: 'es')rescueLingoDotDev::ValidationError=>e# Invalid input or configurationputs"Validation error: #{e.message}"rescueLingoDotDev::AuthenticationError=>e# Invalid API key or authentication failureputs"Authentication error: #{e.message}"rescueLingoDotDev::ServerError=>e# Server-side error (5xx)puts"Server error: #{e.message}"rescueLingoDotDev::APIError=>e# General API errorputs"API error: #{e.message}"rescueLingoDotDev::Error=>e# Base error class for all SDK errorsputs"Error: #{e.message}"end

Exception hierarchy

  • LingoDotDev::Error (base class)
    • LingoDotDev::ArgumentError
      • LingoDotDev::ValidationError - Invalid input or configuration
    • LingoDotDev::APIError - API request errors
      • LingoDotDev::AuthenticationError - Authentication failures
      • LingoDotDev::ServerError - Server-side errors (5xx)

Development

After checking out the repository, run bin/setup to install dependencies.

To run the test suite:

# Set your API keyexport LINGODOTDEV_API_KEY='your-api-key'# Run tests bundle exec rspec

You can also run bin/console for an interactive prompt to experiment with the SDK.

To install this gem onto your local machine, run:

bundle exec rake install

Requirements

  • Ruby >= 3.2.0

Dependencies

  • json ~> 2.0
  • nokogiri ~> 1.0

License

See the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published