Ruby SDK

Use the Ruby SDK to moderate content, manage assets and handle events from your server. It requires Ruby 3.3 or later and has no runtime dependencies.

Install

gem install calmlens

For Bundler, add gem "calmlens" to your Gemfile. Its RBS signatures type every method's options and every result, so you can check your code with Steep.

See Versioning and support for what each version change means and where to find the changelog.

Moderate content

Keep credentials on your server. Create an API key and copy your project ID in the portal; see Authentication for the permissions each call needs. assets.create returns without waiting for the decision; assets.classify and text.classify wait for it. Documents, websites, audio and video always run in the background. See Waiting for the decision for supported content, webhooks and polling.

require 'calmlens'
client = CalmLens::ServerClient.new # reads CALMLENS_API_KEY and CALMLENS_PROJECT_ID
asset = client.text.classify(text: 'Great photo!', external_id: 'comment-42')
puts "Publish #{asset.id}" if %w[allowed limited].include?(asset.classification.moderation.decision)

Without api_key: and project_id:, the client reads CALMLENS_API_KEY and CALMLENS_PROJECT_ID from the environment, and CALMLENS_BASE_URL for the base URL when it is set.

Methods take the ID they act on as their first argument and everything else as snake_case keywords: client.assets.update(asset_id, name: 'Beach'). Nested options are snake_case too, such as processing_options: {features: {face_detection: {enabled: true, age_estimation: true}}}, and keys inside metadata are sent as you wrote them. A keyword the method doesn't take, such as a misspelt one, raises CalmLens::InvalidArgumentError before anything is sent. Every method also takes request_options: for per-call timeouts, retries, idempotency keys and headers; see Request options.

Results are objects with snake_case readers, such as asset.classification.moderation.decision. Read a field by name with asset[:external_id] or asset['externalId'], use asset.to_h for the API's JSON, and match results with case asset in {classification: {moderation: {decision: 'allowed'}}}. Fields CalmLens adds later are kept: they have no reader method, but [] and to_h return them. See Results.

Publish allowed content normally and limited content with reduced reach; see Limited assets. Serve an age-restricted one only to viewers your app allows, by passing viewer_claims: {age_confirmed: true} to the CDN methods or to cdn.sign_asset_url, which add them to the URL; a signed URL or your API key alone doesn't serve it. See Age-restricted assets. Statuses and fields added to the API later are returned unchanged. Treat a status you don't recognise as not allowed. See Reading classification results.

Waiting for a decision

assets.wait_for_decision retrieves the asset at once, then again after 0.5 seconds, waiting 1.5 times longer each time, up to 2 seconds between checks, and returns it once its classification.status is completed or failed. If there's no decision within timeout: seconds (default 60), it raises CalmLens::TimeoutError with code sdk/timeout, and details holds 'assetId' and the last 'classificationStatus' and 'moderationDecision'. To stop waiting early, stop the thread running the call.

queued = client.assets.create(name: 'note.txt', content: {data: 'Hello', type: 'text/plain'})
decided = client.assets.wait_for_decision(queued.id, timeout: 30)

Uploads

Uploads accept plain text, base64, a binary String or an IO. An IO is streamed without being read into memory. Files, Tempfiles and StringIOs know their size; a pipe or socket of unknown length is sent with chunked transfer encoding, or pass size_in_bytes: when you know it.

File.open('clip.mp4', 'rb') do |file|
  client.assets.create(name: 'clip.mp4', content: {data: file, type: 'video/mp4'})
end

Content larger than 8 MiB (part_size_bytes:) that the client can read again, such as a binary String or a File, is uploaded in parts for you: each part is retried on its own, and calling again with the same request_options: {idempotency_key:} resumes an interrupted upload. To send parts yourself, start with part:; whether a multipart upload was started with assets.create (returns without waiting) or assets.classify (waits for the decision) is fixed by the first part, so later parts can come from another process; pass total_size_in_bytes: at the start if you know the file size. See Multipart uploads.

Each upload must be a supported type within that type's size and duration limits; see Asset types and limits. Documents are PDF, DOCX, DOC, RTF and ODT files, spreadsheets (XLSX, XLSM, XLS, ODS) and presentations (PPTX, PPTM, PPT, ODP). Keynote and Numbers files are refused with 415 upload/unsupported-type.

Metadata is a list of {id, value} items, such as metadata: [{id: 'campaign.id', value: 'launch-2026'}]. The value can be any JSON value. To filter or group assets by an item in the portal, use the ID of a metadata field defined there; see Asset metadata.

Upload presets

Pass upload_preset_id: on assets.create and assets.classify to apply an upload preset's folder, visibility, file types, size limit, moderation policy and processing options. To let a browser upload through a preset that requires tokens, sign a single-use token on your server with client.upload_tokens.sign(upload_preset_id: ...). Signing happens locally with your API key and makes no request.

CDN methods

To upload a public image for delivery, retain its content and use an API key with Create assets (assets:create) and Share assets (assets:share). Keep the image unpublished until moderation allows it, then use its rendered CDN resource. For a private image, keep visibility private and sign its URL on your server with a key that has Share assets. See Authentication.

File.open('photo.jpg', 'rb') do |file|
  image = client.assets.classify(name: 'photo.jpg', content: {data: file, type: 'image/jpeg'},
    visibility: 'public', processing_options: {retain_content: true})
  if image.classification.moderation.decision == 'allowed'
    src = client.cdn.get_asset_url(asset_id: image.id, resource: 'rendered')
  end
end

Fetch retained content directly from your backend with client.cdn.serve:

result = client.cdn.serve(asset_id: "asset_e5Gm2Rk8XqT3wLp9VbN4", resource: "original")
puts result

The response contains raw content bytes, not the asset report. Check the response status before using the body; for text assets (such as those created by text.classify), decode the body as UTF-8 text. Give cdn.serve a block to stream the body instead of holding it in memory:

File.open('photo.jpg', 'wb') do |file|
  client.cdn.serve(asset_id: asset_id) do |response|
    raise "CDN returned #{response.status}" unless response.success?
    response.each_chunk { |chunk| file.write(chunk) }
  end
end

The request uses your server API key; private reads require Download assets permission. For private content in browsers, sign the asset URL with cdn.sign_asset_url instead (see Signed asset URLs).

Upload with processing_options: {retain_content: true} to retain content. The CDN delivers by the current classification.moderation.decision, and still requires available content and authorised access. See Delivery while moderation runs.

Methods

The Ruby SDK reference lists client settings and each area's options in detail.

MethodPurpose
text.classify(text:, ...)Classify text and wait for the decision.
assets.create(...)Upload content and return without waiting for the decision.
assets.classify(...)Upload content and wait for the decision where supported.
assets.upload_part(asset_id, ...)Send the next part of a multipart upload.
assets.retrieve(asset_id)Fetch one asset.
assets.retrieve_by_external_id(external_id)Fetch the asset with that external_id.
assets.wait_for_decision(asset_id, timeout:)Retrieve an asset until it is completed or failed; see Waiting for a decision.
assets.list_timeline(asset_id, cursor:, page_size:)Page through an audio or video asset's findings timeline Preview, in time order.
assets.list(...)List one page of assets. filter: 'folderId==fldr_…' lists one folder's assets.
assets.search(query:, ...)Search assets by meaning and by name, ID, external ID, description and tags, best match first; see Asset search.
assets.list_children(asset_id)List an asset's extracted children.
assets.update(asset_id, ...)Update asset fields.
assets.move(asset_id, folder_id:)Move an asset to a folder, or to the project root with nil.
assets.retry(asset_id)Retry an eligible processing failure.
assets.decide(asset_id, decision:, note:)Record a reviewer's decision (allowed, limited, age-restricted, blocked or purged) with a required note. An asset pending moderation can only be blocked or purged, and purging needs confirm_purge: true; see POST /assets/:assetId/decision.
assets.request_review(asset_id, note:)Send an asset to the human review queue, such as when a user reports it. note: is optional.
assets.remove_content(asset_id)Remove stored content and keep the asset record and report.
assets.delete(asset_id)Delete the asset record and its content.
assets.batch(asset_ids:, operation:)Delete up to 500 assets ('delete') or remove their stored content ('remove-content') in one queued request; see POST /projects/:projectId/assets/batch.
folders.list, folders.retrieve, folders.create, folders.update, folders.move, folders.deleteManage folders. folders.list returns a page of up to 50 root folders by name by default, with the ancestors needed to show their paths. Only empty folders can be deleted.
hash_lists.list, hash_lists.retrieve, hash_lists.create, hash_lists.update, hash_lists.deleteManage hash lists that image uploads are compared with.
hash_lists.list_entries, hash_lists.add_entry, hash_lists.remove_entryManage the hashes in a hash list.
policies.list, policies.retrieve, policies.retrieve_assigned, policies.create, policies.update, policies.reset, policies.upgrade, policies.set_automatic_updates, policies.delete, policies.assignManage the organisation's moderation policies and choose the one the project uses; see Policies.
events.list(...)Read one page of the project event feed, and follow it page by page.
events.retrieve_asset(event)Fetch the asset an event is about, as it is now, or nil for an event without one.
ensure_lens(...) / ensure_lenses(...)Create lenses, or change them to these definitions, by identifier.
lenses.list, lenses.create, lenses.retrieve, lenses.update, lenses.deleteManage the project's lenses one by one.
cdn.get_asset_url(...) / cdn.serve(...)Build a public asset URL or a resource URL beneath it, or stream content.
cdn.sign_asset_url(asset_id:, ...)Sign a private asset's URL for browsers and apps.
cdn.get_asset_info(url)Read an asset URL's display info (/info).
upload_tokens.sign(upload_preset_id:)Sign an upload token locally, without a request.
request(method, path, ...)Call an API endpoint this version has no method for, with the client's authentication, retries and errors; see Custom requests.

Pagination

Every list returns one page: enumerating it yields that page's items, and items, has_more and next_cursor describe it. auto_paging_each yields every item on this page and the pages after it, fetching each page as it goes with the same options, and each_page yields the pages themselves. Without a block both return an Enumerator, so client.assets.list(filter: 'classification.moderation.decision==allowed').auto_paging_each.first(5) requests only the pages it needs. To page yourself, next_page? says whether there is another and next_page fetches it. Set the page size with page_size: (1 to 100, default 50), and sort with sort:, a comma-separated list of fields, each descending when prefixed with -, such as '-createdAt,id'. Assets, hash lists, hash list entries, policies and lenses sort by createdAt and id; folders by name (the default) or createdAt. Treat the cursor as opaque.

page = client.folders.list(parent_id: folder_id, sort: '-createdAt')
page.each { |folder| puts folder.name }
page = page.next_page if page.next_page?
client.assets.list_children(asset_id).auto_paging_each { |child| puts child.id }

The event feed's next_cursor is never nil. events.list without cursor: returns no events and a next_cursor for the current time; each_page yields the pages after a cursor until has_more is false, continuing past empty pages. Persist each page's next_cursor once its events are handled. See Reading the feed for event cursors.

cursor = client.events.list.next_cursor # no events; starts from now
client.events.list(cursor: cursor, page_size: 50).each_page do |page|
  page.each { |event| puts event.type }
  cursor = page.next_cursor
end

Errors and retries

Every error is a CalmLens::Error with code, status, request_id (from X-Request-Id, or the error body's requestId), headers, retry_after (whole seconds), details (the API's details object, such as validation issues, or nil) and the original exception in cause. An API error also has body, the response body as received (such as a proxy's HTML page), http_method and url. CalmLens::ErrorCodes lists the API's error codes. Subclasses let you rescue by kind:

ClassRaised for
CalmLens::NotFoundError, RateLimitError, ConflictError, PayloadTooLargeError (413), UnprocessableEntityError (422) and the other APIError classesAPI error responses
ConnectionError, TimeoutErrorNo response arrived; TimeoutError also when wait_for_decision runs out of time
InvalidArgumentError (sdk/invalid-argument), ConfigurationError (sdk/invalid-config)Problems found before anything is sent, including an option the method doesn't take, such as a misspelt external_id
FailureWhat the SDK doesWhat you do
Connection failure or timeoutRetries reads, uploads and cdn.serve up to max_retries: times (default 2), waiting 0.5 seconds and twice as long each time after that (up to max_retry_delay:, 8 seconds by default), half of each wait randomOnce retries run out, retry later: retryable? is true
429, 500, 502, 503, 504 or 409 idempotency/request-in-progressRetries the same requests, waiting for Retry-After (seconds or an HTTP date) when the API sends oneA Retry-After over 60 seconds is raised to you instead: wait, then retry
wait_for_decision runs out of timeRaises TimeoutError (sdk/timeout)Wait again, or rely on a webhook
Failure of another write, such as assets.update or assets.deleteRetried only when you pass request_options: {idempotency_key: '...'}Pass a key when repeating the change must be safe
Upload from an IO that can't rewind, such as a pipeSent onceUpload again from the start
Upload retried from another processEach call sends a new Idempotency-Key, reused for its own retriesPass request_options: {idempotency_key: '...'}
RedirectNot followed; fails with sdk/http-error and the redirect's statusCheck base_url: and cdn_base_url:
cdn.serve failureRetries the same failures, then returns the last responseCheck response.status
SettingDefaultLimits
timeout:120 secondsEach socket read or write, not the whole transfer
open_timeout:10 secondsConnecting
upload_timeout:NoneEach binary upload attempt as a whole
max_response_bytes:32 MiBThe response body the client reads; a larger one fails with sdk/response-too-large
part_size_bytes:8 MiBContent larger than this is uploaded in parts of this size, from 5 to 64 MiB

Override any of them per call with request_options:, or pass request_options: {deadline_ms: 10_000} to bound the whole call, retries included. See Retrying requests safely, and Errors and Retries and timeouts for every error class and the backoff rules.

Reuse one client: it pools keep-alive connections, is safe across threads and reconnects in forked worker processes. Call close when finished. To see each request, set CALMLENS_LOG=info (or debug) or pass logger:; see Logging and metrics.

Webhooks

Verify the exact raw body, then parse it, with CalmLens.parse_webhook_event. It raises CalmLens::WebhookVerificationError with sdk/invalid-webhook-signature for an invalid signature or stale timestamp, or with sdk/invalid-webhook-payload for a verified body that isn't a CalmLens event, such as one without createdAt or projectId. Passing an already parsed Hash instead of the raw body raises CalmLens::InvalidArgumentError (sdk/invalid-argument).

In Rails, read request.raw_post:

event = CalmLens.parse_webhook_event(
  payload: request.raw_post,
  signature: request.headers[CalmLens::WEBHOOK_SIGNATURE_HEADER],
  timestamp: request.headers[CalmLens::WEBHOOK_TIMESTAMP_HEADER],
  secret: ENV.fetch('CALMLENS_WEBHOOK_SECRET')
)

In Sinatra or another Rack app, read request.body.read and pass the headers with headers: request.env:

event = CalmLens.parse_webhook_event(payload: request.body.read, headers: request.env,
                                     secret: ENV.fetch('CALMLENS_WEBHOOK_SECRET'))

headers: also takes a Hash with names in any case, where a repeated header is an Array of its values, or Net::HTTPHeader. The event is a CalmLens::Event, the same as an events.list item: event.id, project_id, type, severity, title, description, asset_id, asset_sequence, facts and created_at, where description, asset_id and asset_sequence are nil when the event has none. Events carry only the asset's ID: client.events.retrieve_asset(event) returns the asset as it is now. Fields CalmLens adds later are kept: event.to_h returns the whole body as received.

Respond quickly and process the event afterwards, for example in a background job. Deduplicate by the event's id: redeliveries have a new x-calmlens-delivery ID but keep the same event ID. CalmLens.verify_webhook_signature and CalmLens.verify_webhook_request(payload:, headers:, secret:) return true or false instead of raising. event.test? and CalmLens.test_webhook_event?(event) are true for a test send from the portal or CLI. See Webhooks, and Webhooks in the reference for header constants and the signature tolerance.

Deduplicating by event.id stops a redelivery being applied twice, but it doesn't put events in order: a retry can arrive after a later event about the same asset. Store the highest asset_sequence you've applied for each asset, and apply an event only when event.newer_than?(last_sequence) is true, so a late asset.allowed never undoes a later asset.blocked. See Event order.

Test webhooks locally

Your tests and CI need no CLI: the testing helpers build and sign deliveries offline, so your handler's verification runs unchanged. To forward your project's real events to a handler on your machine, install the calmlens CLI, a standalone executable for macOS, Linux and Windows:

curl -fsSL https://calmlens.com/install.sh | sh

Then run calmlens login and calmlens listen --forward-to <url>. See Local development for Windows, Homebrew, release downloads and npm, sending portal test events through a tunnel, and creating test events with calmlens trigger.

Testing

Use CalmLens::MockServerClient from calmlens/testing for offline tests. See Ruby testing.

Last updated

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies