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

# Exemplos em Ruby

> Integração com Net::HTTP e Sidekiq

## Cliente Ruby

```ruby theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
require 'net/http'
require 'json'

class ShappireClient
  BASE = 'https://api.shappire.tools/v1'

  def initialize(api_key = ENV.fetch('SHAPPIRE_API_KEY'))
    @api_key = api_key
  end

  def resolve(url)
    post('/media/resolve', { url: url })
  end

  def enqueue(media_id:, format:)
    post('/media/download', { media_id: media_id, format: format })['job_id']
  end

  def job(job_id)
    get("/jobs/#{job_id}")
  end

  def wait_job(job_id, interval: 3, timeout: 300)
    started = Time.now
    loop do
      data = job(job_id)
      return data if data['status'] == 'completed'
      raise 'job failed' if data['status'] == 'failed'
      raise 'timeout' if Time.now - started > timeout
      sleep interval
    end
  end

  private

  def get(path)
    request(Net::HTTP::Get, path)
  end

  def post(path, body)
    request(Net::HTTP::Post, path, body)
  end

  def request(klass, path, body = nil)
    uri = URI("#{BASE}#{path}")
    req = klass.new(uri)
    req['X-API-Key'] = @api_key
    req['Content-Type'] = 'application/json'
    req.body = body.to_json if body

    res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
    json = JSON.parse(res.body)
    raise json.dig('error', 'message') if res.code.to_i >= 400
    json['data']
  end
end
```

## Sidekiq worker

```ruby theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
class MediaDownloadWorker
  include Sidekiq::Worker

  def perform(url)
    client = ShappireClient.new
    media = client.resolve(url)
    job_id = client.enqueue(media_id: media['id'], format: 'video_best')
    result = client.wait_job(job_id)
    # salvar result['result']['download_url']
  end
end
```

## Rails controller

```ruby theme={"theme":{"light":"github-light","dark":"one-dark-pro"}}
class DownloadsController < ApplicationController
  def create
    MediaDownloadWorker.perform_async(params[:url])
    render json: { status: 'queued' }
  end
end
```
