> ## Documentation Index
> Fetch the complete documentation index at: https://docs.straddle.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Ruby SDK for Straddle

> Install and configure the official Straddle Ruby SDK. Authenticate, make API calls, handle errors, and integrate ACH payments into your Ruby application.

The Straddle Ruby library provides convenient access to the Straddle REST API from any Ruby 3.2.0+ application. The library includes comprehensive support for all API endpoints with built-in error handling.

<Info>
  The SDK supports Ruby 3.2.0+ and provides a clean, idiomatic Ruby interface to the Straddle API.
</Info>

## Installation

Install the SDK by adding it to your application's `Gemfile`:

```ruby theme={null}
gem "straddle"
```

Then run:

```bash theme={null}
bundle install
```

For development environments, we recommend using [dotenv](https://github.com/bkeepers/dotenv) to manage your API keys:

```ruby theme={null}
gem "dotenv", groups: [:development, :test]
```

## Setup and Configuration

<Steps>
  <Step title="Require the SDK" icon="file-import">
    Require the necessary gems in your Ruby application:

    ```ruby theme={null}
    require "bundler/setup"
    require "straddle"
    ```
  </Step>

  <Step title="Initialize the Client" icon="gear">
    Create a new instance of the Straddle client:

    ```ruby theme={null}
    straddle = Straddle::Client.new(
      api_key: ENV["STRADDLE_API_KEY"], # This is the default and can be omitted
      environment: "sandbox" # or "production", defaults to "sandbox"
    )
    ```

    <Warning>
      Never hardcode your API key directly in your code. Use environment variables or a secure configuration
      management system.
    </Warning>
  </Step>
</Steps>

## Implementation Examples

<Tip>
  The Straddle Ruby SDK uses symbols for hash keys in method parameters. This follows Ruby conventions and provides better performance than string keys.
</Tip>

<Tabs>
  <Tab title="Straddle Account Customers">
    For account customers (non-platform), the flow is simpler as the account context is inferred from the API key:

    ```ruby theme={null}
    require "bundler/setup"
    require "straddle"

    # Initialize the client
    straddle = Straddle::Client.new(
      api_key: ENV["STRADDLE_API_KEY"],
      environment: "sandbox"
    )

    # 1. Create a customer
    customer_response = straddle.customers.create(
      device: { ip_address: "192.168.0.1" },
      email: "customer@example.com",
      name: "Customer Name",
      phone: "+15555555555",
      type: "individual"
    )
    customer = customer_response.data

    # 2. Link a bank account
    paykey_response = straddle.bridge.link.bank_account(
      customer_id: customer.id,
      routing_number: "011000028",
      account_number: "000123456789",
      account_type: "checking"
    )
    paykey = paykey_response.data

    # 3. Create a charge
    charge = straddle.charges.create(
      amount: 100, # Amount in cents ($1.00)
      config: { balance_check: "required" },
      consent_type: "internet",
      currency: "USD",
      description: "Monthly subscription fee",
      device: { ip_address: "192.168.1.1" },
      external_id: "external_id",
      paykey: paykey.paykey,
      payment_date: "2025-01-30" # Can also use Date objects: Date.new(2025, 1, 30) # Can also use Date objects: Date.new(2025, 1, 30)
    )
    puts charge.data
    ```
  </Tab>

  <Tab title="Embed Customers">
    This example demonstrates the complete flow for Embed customers:

    ```ruby theme={null}
    require "bundler/setup"
    require "straddle"

    # Initialize the client
    straddle = Straddle::Client.new(
      api_key: ENV["STRADDLE_API_KEY"],
      environment: "sandbox"
    )

    # 1. Create an organization
    org_response = straddle.embed.organizations.create(
      name: "SDK Test Organization in Sandbox"
    )
    organization = org_response.data

    # 2. Create an account for the organization
    account_response = straddle.embed.accounts.create(
      organization_id: organization.id,
      account_type: "business",
      business_profile: {
        name: "SDK Test",
        website: "straddle.com"
      },
      access_level: "standard"
    )
    account = account_response.data

    # 3. Create a customer
    customer_response = straddle.customers.create(
      straddle_account_id: account.id,
      device: { ip_address: "192.168.0.1" },
      email: "customer@example.com",
      name: "Customer Name",
      phone: "+15555555555",
      type: "individual"
    )
    customer = customer_response.data

    # 4. Link a bank account
    paykey_response = straddle.bridge.link.bank_account(
      straddle_account_id: account.id,
      customer_id: customer.id,
      routing_number: "011000028",
      account_number: "000123456789",
      account_type: "checking"
    )
    paykey = paykey_response.data

    # 5. Create a charge
    charge = straddle.charges.create(
      straddle_account_id: account.id,
      amount: 100, # Amount in cents ($1.00)
      config: { balance_check: "required" },
      consent_type: "internet",
      currency: "USD",
      description: "Monthly subscription fee",
      device: { ip_address: "192.168.1.1" },
      external_id: "external_id",
      paykey: paykey.paykey,
      payment_date: "2025-01-30"
    )
    puts charge.data
    ```
  </Tab>
</Tabs>

## Key Features

<CardGroup cols={2}>
  <Card title="Idiomatic Ruby" icon="gem">
    Clean, Ruby-style interface following community conventions with snake\_case methods and intuitive hash parameters.
  </Card>

  <Card title="Thread Safety" icon="lock">
    The client is thread-safe, allowing you to share a single instance across multiple threads in your application.
  </Card>

  <Card title="Automatic Retries" icon="arrows-rotate">
    Built-in retry logic for transient errors with configurable retry strategies.
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation">
    Comprehensive error classes that map to HTTP status codes for precise error handling.
  </Card>
</CardGroup>

## Error Handling

The SDK provides specific exception types for different error cases:

<AccordionGroup>
  <Accordion icon="bug" title="Common Error Types">
    ```ruby theme={null}
    begin
      charge = straddle.charges.create(
        amount: 1000,
        currency: "USD",
        # ... other required params
      )
    rescue Straddle::Errors::BadRequestError => e
      puts "Bad request: #{e.message}"
      puts "Status: #{e.status_code}"
      puts "Response body: #{e.response_body}" if e.respond_to?(:response_body)
    rescue Straddle::Errors::UnprocessableEntityError => e
      puts "Validation error: #{e.message}"
      puts "Errors: #{e.errors}" if e.respond_to?(:errors)
    rescue Straddle::Errors::AuthenticationError => e
      puts "Authentication failed: #{e.message}"
    rescue Straddle::Errors::PermissionDeniedError => e
      puts "Permission denied: #{e.message}"
    rescue Straddle::Errors::NotFoundError => e
      puts "Resource not found: #{e.message}"
    rescue Straddle::Errors::RateLimitError => e
      puts "Rate limit exceeded: #{e.message}"
      puts "Retry after: #{e.retry_after}" if e.respond_to?(:retry_after)
    rescue Straddle::Errors::InternalServerError => e
      puts "Server error: #{e.message}"
    rescue Straddle::Errors::APIError => e
      # Catch all other API errors
      puts "API error: #{e.message}"
    end
    ```

    Common error types include:

    * `BadRequestError` (400)
    * `UnprocessableEntityError` (422)
    * `AuthenticationError` (401)
    * `PermissionDeniedError` (403)
    * `NotFoundError` (404)
    * `RateLimitError` (429)
    * `InternalServerError` (>=500)
  </Accordion>

  <Accordion icon="clock" title="Timeout Configuration">
    Configure request timeouts:

    ```ruby theme={null}
    # Configure timeout in seconds
    straddle = Straddle::Client.new(
      api_key: ENV["STRADDLE_API_KEY"],
      timeout: 30 # 30 seconds
    )

    # Or configure with more granular settings
    straddle = Straddle::Client.new(
      api_key: ENV["STRADDLE_API_KEY"],
      timeout: {
        connect: 5,
        read: 30,
        write: 10
      }
    )
    ```
  </Accordion>

  <Accordion icon="arrows-rotate" title="Retry Configuration">
    Configure automatic retries:

    ```ruby theme={null}
    straddle = Straddle::Client.new(
      api_key: ENV["STRADDLE_API_KEY"],
      max_retries: 3,
      retry_delay: 1.0 # seconds
    )
    ```
  </Accordion>
</AccordionGroup>

## SDK Requirements

<CardGroup cols={2}>
  <Card title="Ruby Version" icon="gem">
    Ruby 3.2.0 or higher
  </Card>

  <Card title="Bundler" icon="box">
    Bundler for dependency management
  </Card>
</CardGroup>

For more detailed information about the SDK structure and usage, refer to our [API Documentation](https://docs.straddle.com) and [GitHub repository](https://github.com/straddleio/straddle-ruby).
