百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
T

temporal-ruby

> 编程语言
开源

Temporal 的 Ruby SDK

286 stars0 点赞3 次浏览
访问官网GitHub

工具介绍

Temporal 的 Ruby SDK

Ruby SDK for Temporal

A pure Ruby library for defining and running Temporal workflows and activities.

To find more about Temporal itself please visit .

Getting Started

Clone this repository:

bash
git clone [email protected]:coinbase/temporal-ruby.git

Include this gem to your Gemfile:

ruby
gem 'temporal-ruby', github: 'coinbase/temporal-ruby'

Define an activity:

ruby
require 'temporal-ruby'
class HelloActivity .

There are plenty of [runnable examples](examples/) demonstrating various features of this library
available, make sure to check them out.

## Installing dependencies

Temporal service handles all the persistence, fault tolerance and coordination of your workflows and
activities. To set it up locally, download and boot the Docker Compose file from the official repo.
The Docker Compose file forwards all ports to your localhost so you can interact with
the containers easily from your shells.

Run:

```sh
curl -O https://raw.githubusercontent.com/temporalio/docker-compose/main/docker-compose.yml

docker-compose up

Using Credentials

SSL

In many production deployments you will end up connecting to your Temporal Services via SSL. In this case you must read the public certificate of the CA that issued your Temporal server's SSL certificate and create an instance of gRPC Channel Credentials.

Configure your Temporal connection:

ruby
Temporal.configure do |config|
    config.host = 'localhost'
    config.port = 7233
    config.namespace = 'ruby-samples'
    config.task_queue = 'hello-world'
    config.credentials = GRPC::Core::ChannelCredentials.new(root_cert, client_key, client_chain)
end

OAuth2 Token

Use gRPC Call Credentials to add OAuth2 token to gRPC calls:

ruby
Temporal.configure do |config|
    config.host = 'localhost'
    config.port = 7233
    config.namespace = 'ruby-samples'
    config.task_queue = 'hello-world'
    config.credentials = GRPC::Core::CallCredentials.new(updater_proc)
end

updater_proc should be a method that returns proc. See an example of updater_proc in googleauth library.

Combining Credentials

To configure both SSL and OAuth2 token cedentials use compose method:

ruby
Temporal.configure do |config|
    config.host = 'localhost'
    config.port = 7233
    config.namespace = 'ruby-samples'
    config.task_queue = 'hello-world'
    config.credentials = GRPC::Core::ChannelCredentials.new(root_cert, client_key, client_chain).compose(
        GRPC::Core::CallCredentials.new(token.updater_proc)
    )
end

Configuration

This gem is optimised for the smoothest out-of-the-box experience, which is achieved using a global configuration:

ruby
Temporal.configure do |config|
  config.host = '127.0.0.1' # sets global host
  ...
end

Temporal::Worker.new # uses global host
Temporal.start_workflow(...) # uses global host

This will work just fine for simpler use-cases, however at some point you might need to setup multiple clients and workers within the same instance of your app (e.g. you have different Temporal hosts, need to use different codecs/converters for different parts of your app, etc). Should this be the case we recommend using explicit local configurations for each client/worker:

ruby
config_1 = Temporal::Configuration.new
config_1.host = 'temporal-01'

config_2 = Temporal::Configuration.new
config_2.host = 'temporal-01'

worker_1 = Temporal::Worker.new(config_1)
worker_2 = Temporal::Worker.new(config_2)

client_1 = Temporal::Client.new(config_1)
client_1.start_workflow(...)

client_2 = Temporal::Client.new(config_2)
client_2.start_workflow(...)

…

ruby
class RenewSubscriptionWorkflow  e
    CancelSubscriptionActivity.execute!(subscription[:id])
    SendSubscriptionCancellationEmailActivity.execute!(user_id, subscription[:id])
  end
end

In this simple workflow we are checking if a user has an active subscription and then attempt to charge their credit card to renew an expired subscription, notifying the user of the outcome. All the work is encapsulated in activities, while the workflow itself is responsible for calling the activities in the right order, passing values between them and handling failures.

There is a couple of ways to execute an activity from your workflow:

ruby
# Calls the activity by its class and blocks the execution until activity is
# finished. The return value of your activity will get assigned to the result
result = MyActivity.execute!(arg1, arg2)

# Here's a non-blocking version of the execute, returning back the future that
# will get fulfilled when activity completes. This approach allows modelling
# asynchronous workflows with activities executed in parallel
future = MyActivity.execute(arg1, arg2)
result = future.get

# Full versions of the calls from above, but has more flexibility (shown below)
result = workflow.execute_activity!(MyActivity, arg1, arg2)
future = workflow.execute_activity(MyActivity, arg1, arg2)

# In case your workflow code does not have access to activity classes (separate
# process, activities implemented in a different language, etc), you can
# simply reference them by their names
workflow.execute_activity('MyActivity', arg1, arg2, options: { namespace: 'my-namespace', task_queue: 'my-task-queue' })

Besides calling activities workflows can:

  • Use timers
  • Receive signals
  • Execute other (child) workflows
  • Respond to queries

Activities

An activity is a basic unit of work that performs the desired action (potentially causing side-effects). It can return a result or raise an error. It is defined like so:

ruby
class CloseUserAccountActivity < Temporal::Activity
  class UserNotFound < Temporal::ActivityException; end

  def execute(user_id)
    user = User.find_by(id: user_id)

    raise UserNotFound, 'User with specified ID does not exist' unless user

    user.close_account
    user.save

    AccountClosureEmail.deliver(user)

    return nil
  end
end

…

ruby
class AsyncActivity < Temporal::Activity
  def execute(user_id)
    user = User.find_by(id: user_id)

    # Pass the async_token to complete your activity later
    ExternalSystem.verify_user(user, activity.async_token)

    activity.async # prevents activity from completing immediately
  end
end

Later when a confirmation is received you'll need to complete your activity manually using the token provided:

ruby
Temporal.complete_activity(async_token, result)

Similarly you can fail the activity by calling:

ruby
Temporal.fail_activity(async_token, MyError.new('Something went wrong'))

…

ruby
require 'temporal/worker'

worker = Temporal::Worker.new
worker.register_workflow(HelloWorldWorkflow)
worker.register_activity(SomeActivity)
worker.register_activity(SomeOtherActivity)
worker.start

A call to worker.start will take over the current process and will keep it unning until a TERM or INT signal is received. By only registering a subset of your workflows/activities with a given worker you can split processing across as many workers as you need.

Starting a workflow

All communication is handled via Temporal service, so in order to start a workflow you need to send a message to Temporal:

ruby
Temporal.start_workflow(HelloWorldWorkflow)

Optionally you can pass input and other options to the workflow:

ruby
Temporal.start_workflow(RenewSubscriptionWorkflow, user_id, options: { workflow_id: user_id })

…

ruby
Temporal.schedule_workflow(HealthCheckWorkflow, '*/5 * * * *')

…


class MyMiddleware
  def call(metadata)
    puts "Before execution"
    yield
    puts "After execution"
    result
  end
end

…

ruby
class MyWorkflow < Temporal::Workflow
  def execute
    ActivityOld1.execute!

    workflow.sleep(10)

    ActivityOld2.execute!

    return nil
  end
end

which got updated to:

ruby
class MyWorkflow < Temporal::Workflow
  def execute
    Activity1.execute!

    if workflow.has_release?(:fix_1)
      ActivityNew1.execute!
    end

    workflow.sleep(10)

    if workflow.has_release?(:fix_1)
      ActivityNew2.execute!
    else
      ActivityOld.execute!
    end

    if workflow.has_release?(:fix_2)
      ActivityNew3.execute!
    end

    return nil
  end
end

…

ruby
require 'temporal/testing'

This will allow you to execute workflows locally by running HelloWorldWorkflow.execute_locally. Any arguments provided will forwarded to your #execute method.

In case of a higher level end-to-end integration specs, where you need to execute a Temporal workflow as part of your code, you can enable local testing:

ruby
Temporal::Testing.local!

This will treat every Temporal.start_workflow call as local and perform your workflows inline. It also works with a block, restoring the original mode back after the execution:

ruby
Temporal::Testing.local! do
  Temporal.start_workflow(HelloWorldWorkflow)
end

Make sure to check out example integration specs for more details. Instructions for running these integration specs can be found in examples/README.md.

TODO

There's plenty of work to be done, but most importanly we need:

  • Write specs for everything
  • Implement support for missing features

LICENSE

Copyright 2020 Coinbase, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Issues· 70 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言