### Create and Run an Example Script (Ruby) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Demonstrates how to create and execute example scripts for the SDK. Requires making the script executable and then running it with the Ruby interpreter. ```ruby #!/usr/bin/env ruby # frozen_string_literal: true require_relative "../lib/moderation_api" # ... ``` ```bash $ chmod +x './examples/.rb' # run the example against your api $ ruby './examples/.rb' ``` -------------------------------- ### Preview Project Documentation (Bash) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Generates and serves the project's documentation locally, allowing for previewing. An optional port can be specified. ```bash $ bundle exec rake docs:preview [PORT=8808] ``` -------------------------------- ### Bootstrap Project Dependencies (Bash) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Installs all required dependencies for the project using a bootstrap script. Assumes a Ruby environment is already set up. ```bash $ ./scripts/bootstrap ``` -------------------------------- ### Run Project Tests (Bash) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Executes the test suite for the project. This typically requires a mock server to be running, as indicated in the setup instructions. ```bash $ bundle exec rake test ``` -------------------------------- ### Install SDK from Git (Ruby Gemfile) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Specifies how to include the moderation_api gem in your project's Gemfile by pointing to its Git repository. This allows for direct installation from source control. ```ruby gem "moderation_api", git: "https://www.github.com/moderation-api/sdk-ruby" ``` -------------------------------- ### Set up Mock Server with Prism (Bash) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Instructions to set up a mock server using Prism against an OpenAPI specification. This is a prerequisite for running most tests in the repository. ```bash $ npx prism mock path/to/your/openapi.yml ``` -------------------------------- ### Run Project Rake Tasks (Bash) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Executes all available Rake commands for the project. Running `rake` without arguments displays a list of all runnable commands. ```bash $ bundle exec rake ``` -------------------------------- ### Reference Local SDK Repository (Bash & Ruby) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Provides instructions to clone the SDK repository locally and then reference it in your project's Gemfile using a local path. This is useful for development or testing specific versions. ```bash $ git clone -- 'https://www.github.com/moderation-api/sdk-ruby' '' ``` ```ruby gem "moderation_api", path: "" ``` -------------------------------- ### Lint and Typecheck Project (Bash) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Runs RuboCop for linting and formatting Ruby files, and type checkers like Sorbet or Steep for `.rbi` and `.rbs` files. This command ensures code quality and correctness. ```bash $ bundle exec rake lint ``` -------------------------------- ### Format and Fix Lint Issues (Bash) Source: https://github.com/moderation-api/sdk-ruby/blob/main/CONTRIBUTING.md Automatically formats code and fixes identified linting issues across the project's Ruby files, `.rbi`, and `.rbs` files using configured tools. ```bash $ bundle exec rake format ``` -------------------------------- ### Install Moderation API Ruby Gem Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Add the Moderation API gem to your application's Gemfile to include it as a dependency. This ensures the library is available for use in your project. ```ruby gem "moderation_api", "~> 2.3.0" ``` -------------------------------- ### Initialize Moderation API Client and Submit Content Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Demonstrates how to initialize the Moderation API client with an API key and submit content for moderation. It then prints the moderation recommendation from the response. ```ruby require "bundler/setup" require "moderation_api" moderation_api = ModerationAPI::Client.new( secret_key: ENV["MODAPI_SECRET_KEY"] # This is the default and can be omitted ) response = moderation_api.content.submit(content: {text: "x", type: "text"}) puts(response.recommendation) ``` -------------------------------- ### Client Initialization for Moderation API Ruby Library Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Demonstrates how to initialize the Moderation API client in Ruby. It covers initialization using environment variables, explicit configuration with API endpoint, retry, and timeout settings, and disabling retries. ```ruby require "bundler/setup" require "moderation_api" # Initialize with environment variable (default) client = ModerationAPI::Client.new( secret_key: ENV["MODAPI_SECRET_KEY"] ) # Or with explicit configuration client = ModerationAPI::Client.new( secret_key: "your_secret_key", base_url: "https://api.moderationapi.com/v1", max_retries: 2, timeout: 60.0, initial_retry_delay: 0.5, max_retry_delay: 8.0 ) # Disable retries for specific use cases client = ModerationAPI::Client.new( secret_key: ENV["MODAPI_SECRET_KEY"], max_retries: 0, timeout: 30.0 ) ``` -------------------------------- ### Retrieve Account Information (Ruby) Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Fetch account and organization details, including name, plan, quota usage, and available features. Requires a configured client object. ```ruby # Get account information account = client.account.list puts account.organization_name puts account.plan puts account.quota_used puts account.quota_limit puts account.features ``` -------------------------------- ### Author Management Operations in Ruby Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Illustrates managing author profiles via the Ruby SDK. Covers creating new authors with detailed information, retrieving existing author data, updating author details, listing authors with filtering and pagination, and deleting authors. ```ruby # Create a new author author = client.authors.create( external_id: "user_12345", name: "John Doe", email: "john@example.com", profile_picture: "https://example.com/avatar.jpg", external_link: "https://example.com/profile/johndoe", first_seen: Time.now.to_f, metadata: { account_type: "premium", signup_date: "2024-01-01" } ) puts author.id puts author.trust_level # Retrieve author details author = client.authors.retrieve("user_12345") puts author.name puts author.trust_level puts author.total_content puts author.flagged_content puts author.approved_content # Update author information updated = client.authors.update( "user_12345", name: "John Smith", email: "john.smith@example.com", manual_trust_level: 0.85, last_seen: Time.now.to_f ) # List authors with filtering and pagination authors = client.authors.list( page_number: 1, page_size: 50, sort_by: :trustLevel, sort_direction: :desc, member_since_date: "2024-01-01", last_active_date: "2024-12-01" ) authors.items.each do |author| puts "#{author.name}: Trust Level #{author.trust_level}" end puts "Total: #{authors.total_count}" puts "Page: #{authors.page_number}/#{authors.total_pages}" # Delete an author client.authors.delete("user_12345") ``` -------------------------------- ### Moderation Queue Management in Ruby Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Details how to interact with moderation queues using the Ruby SDK. This includes retrieving queue details, fetching queue statistics, and listing items within a queue with sorting and filtering options. ```ruby # Get queue details queue = client.queue.retrieve("queue_abc123") puts queue.name puts queue.item_count puts queue.description # Get queue statistics stats = client.queue.get_stats( "queue_abc123", within_days: "30" ) puts stats.total_items puts stats.resolved_items puts stats.pending_items puts stats.average_resolution_time # List items in a queue items = client.queue.items.list( "queue_abc123", page_number: 1, page_size: 25, sort_field: :createdAt, sort_direction: :desc, include_resolved: "false" ) items.items.each do |item| puts "Content: #{item.content_id}" puts "Author: #{item.author_id}" puts "Flagged: #{item.flagged_at}" end ``` -------------------------------- ### Content Moderation Submission in Ruby Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Shows how to submit content (text and image) for moderation using the Ruby library. It details including author information, content identifiers, metadata, and handling policy overrides. Responses include recommendation, flagged status, and policy details. ```ruby # Submit text content for moderation response = client.content.submit( content: { text: "Check this message for toxicity and spam", type: "text" }, author_id: "user_12345", content_id: "msg_67890", channel: "chat_general", conversation_id: "thread_abc123", metadata: { ip_address: "192.168.1.1", user_agent: "Mozilla/5.0" } ) puts response.recommendation # "approve" or "flag" or "reject" puts response.flagged # true/false puts response.policies # Array of policy results # Submit without storing (real-time check only) response = client.content.submit( content: {text: "Ephemeral message", type: "text"}, do_not_store: true ) # Override channel policies for enterprise response = client.content.submit( content: {text: "Custom policy check", type: "text"}, policies: [ {type: "toxicity", threshold: 0.8}, {type: "spam", enabled: true} ] ) # Submit image content response = client.content.submit( content: { url: "https://example.com/image.jpg", type: "image" }, author_id: "user_12345", meta_type: :profile_picture ) ``` -------------------------------- ### Manage Custom Moderation Actions (Ruby) Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Create, retrieve, update, list, execute, and delete custom moderation actions. Actions can be configured with types, behavior, value requirements, and webhooks. Requires a configured client object. ```ruby # Create a custom action action = client.actions.create( name: "Ban User", key: "ban_user", description: "Permanently ban user from platform", type: :custom, position: :all_queues, queue_behaviour: :resolve, value_required: true, free_text: false, possible_values: [ {label: "Spam", value: "spam"}, {label: "Harassment", value: "harassment"}, {label: "Terms Violation", value: "terms"} ], webhooks: [ { url: "https://api.example.com/webhooks/ban-user", headers: {"Authorization" => "Bearer token123"} } ] ) puts action.id puts action.key # Retrieve an action action = client.actions.retrieve("action_123") # Update an action updated = client.actions.update( "action_123", name: "Temporary Ban User", description: "Temporarily suspend user account", possible_values: [ {label: "1 day", value: "1d"}, {label: "7 days", value: "7d"}, {label: "30 days", value: "30d"} ] ) # List all actions actions = client.actions.list actions.each do |action| puts "#{action.name} (#{action.key})" end # List actions for specific queue actions = client.actions.list(queue_id: "queue_abc123") # Execute action on content result = client.actions.execute.execute( action_key: "ban_user", content_ids: ["content_123", "content_456"], value: "spam", queue_id: "queue_abc123", duration: 86400000 # 24 hours in milliseconds ) puts result.success puts result.affected_count # Execute action on authors result = client.actions.execute.execute( action_key: "restrict_posting", author_ids: ["user_123", "user_456"], value: "harassment", duration: 604800000 # 7 days ) # Delete an action client.actions.delete("action_123") ``` -------------------------------- ### Provide Typesafe Request Parameters with Sorbet in Ruby Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Demonstrates how to provide typesafe request parameters using Sorbet's RBI definitions. It shows using `ModerationAPI::ContentSubmitParams::Content::Text.new` for type safety, contrasting it with non-typesafe hash usage. ```ruby moderation_api.content.submit(content: ModerationAPI::ContentSubmitParams::Content::Text.new(text: "x")) ``` ```ruby # Hashes work, but are not typesafe: moderation_api.content.submit(content: {text: "x", type: "text"}) # You can also splat a full Params class: params = ModerationAPI::ContentSubmitParams.new( content: ModerationAPI::ContentSubmitParams::Content::Text.new(text: "x") ) moderation_api.content.submit(**params) ``` -------------------------------- ### Pattern Matching on Responses Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Utilizes Ruby's pattern matching feature to concisely handle different response structures based on the recommendation and status. This provides a clean way to branch logic based on API outcomes. ```ruby # Pattern matching on responses case response in {recommendation: "approve"} puts "Content approved" in {recommendation: "flag", flagged: true} puts "Content flagged for review" in {recommendation: "reject"} puts "Content rejected" end ``` -------------------------------- ### Make Custom API Requests Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Enables making arbitrary API requests to any endpoint using specified HTTP methods, paths, query parameters, headers, and request bodies. Useful for interacting with parts of the API not directly exposed by the SDK methods. ```ruby # Make custom API requests response = client.request( method: :post, path: "/custom/endpoint", query: {filter: "active"}, headers: {"X-API-Version" => "2"}, body: {data: "custom payload"} ) ``` -------------------------------- ### Handle Moderation API Errors in Ruby Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Illustrates how to catch and handle various `ModerationAPI::Errors` subclasses that may be raised during API interactions, such as connection issues, rate limiting, or other status errors. ```ruby begin content = moderation_api.content.submit(content: {text: "x", type: "text"}) rescue ModerationAPI::Errors::APIConnectionError => e puts("The server could not be reached") puts(e.cause) # an underlying Exception, likely raised within `net/http` rescue ModerationAPI::Errors::RateLimitError => e puts("A 429 status code was received; we should back off a bit.") rescue ModerationAPI::Errors::APIStatusError => e puts("Another non-200-range status code was received") puts(e.status) end ``` -------------------------------- ### Send Undocumented Parameters to Moderation API Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Explains how to send undocumented query parameters, body parameters, and headers with API requests using `extra_query`, `extra_body`, and `extra_headers`. It also shows how to read undocumented response properties. ```ruby response = moderation_api.content.submit( content: {text: "x", type: "text"}, request_options: { extra_query: {my_query_parameter: value}, extra_body: {my_body_parameter: value}, extra_headers: {"my-header": value} } ) puts(response[:my_undocumented_property]) ``` -------------------------------- ### Manage Wordlists for Content Filtering (Ruby) Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Manage custom wordlists used for content filtering. Operations include listing, retrieving, updating, adding words, removing words, and checking embedding status. Requires a configured client object. ```ruby # List all wordlists wordlists = client.wordlist.list wordlists.each do |list| puts "#{list.name} (#{list.key}): #{list.word_count} words" end # Retrieve a specific wordlist wordlist = client.wordlist.retrieve("wordlist_123") puts wordlist.name puts wordlist.description puts wordlist.words.length # Update wordlist metadata and replace all words updated = client.wordlist.update( "wordlist_123", name: "Banned Terms", description: "Updated list of prohibited words", key: "banned_terms", words: ["spam", "scam", "phishing", "malware"] ) # Add words to existing wordlist result = client.wordlist.words.add( "wordlist_123", words: ["badword1", "badword2", "badword3"] ) puts result.added_count puts result.total_count # Remove words from wordlist result = client.wordlist.words.remove( "wordlist_123", words: ["badword1"] ) puts result.removed_count # Check embedding status status = client.wordlist.get_embedding_status("wordlist_123") puts status.status # "pending", "processing", "complete" puts status.progress # 0.0 to 1.0 puts status.estimated_time # seconds remaining ``` -------------------------------- ### Configure Timeouts and Retries Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Set per-request timeouts and maximum retry attempts for API calls. This ensures that requests do not hang indefinitely and automatically retry in case of transient network issues. ```ruby # Per-request timeout and retry configuration response = client.content.submit( content: {text: "Test", type: "text"}, request_options: { timeout: 30, max_retries: 5 } ) ``` -------------------------------- ### Access Undocumented Response Properties Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Demonstrates how to access fields in the API response that might not be explicitly documented or typed by the SDK. Use with caution as these fields may change without notice. ```ruby # Access undocumented response properties puts response[:undocumented_field] ``` -------------------------------- ### Make Undocumented Endpoint Requests in Ruby Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Allows making requests to undocumented endpoints using `client.request`. This method retains benefits like authentication and retries. It takes `method`, `path`, `query`, `headers`, and `body` as parameters. ```ruby response = client.request( method: :post, path: '/undocumented/endpoint', query: {"dog": "woof"}, headers: {"useful-header": "interesting-value"}, body: {"hello": "world"} ) ``` -------------------------------- ### Send Undocumented Parameters Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Allows sending extra query parameters, body parameters, and headers that may not be explicitly defined in the SDK's schema. Useful for accessing experimental features or custom endpoints. ```ruby # Send undocumented parameters response = client.content.submit( content: {text: "Test", type: "text"}, request_options: { extra_query: {custom_param: "value"}, extra_body: {experimental_flag: true}, extra_headers: {"X-Custom-Header" => "value"} } ) ``` -------------------------------- ### Configure Max Retries for Moderation API Requests Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Shows how to configure the maximum number of automatic retries for API requests, either globally for the client or on a per-request basis. Setting `max_retries` to 0 disables retries. ```ruby # Configure the default for all requests: moderation_api = ModerationAPI::Client.new( max_retries: 0 # default is 2 ) # Or, configure per-request: moderation_api.content.submit(content: {text: "x", type: "text"}, request_options: {max_retries: 5}) ``` -------------------------------- ### Use Typed Parameters with Sorbet Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Leverages Sorbet, a static type checker for Ruby, to provide type safety for request parameters. This improves code maintainability and helps catch errors during development. ```ruby # Use typed parameters with Sorbet response = client.content.submit( content: ModerationAPI::ContentSubmitParams::Content::Text.new( text: "Fully typed content" ) ) ``` -------------------------------- ### Configure Request Timeout for Moderation API Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Demonstrates how to set the request timeout duration for API calls. The timeout can be configured globally or per request. Setting `timeout` to `nil` disables timeouts. ```ruby # Configure the default for all requests: moderation_api = ModerationAPI::Client.new( timeout: nil # default is 60 ) # Or, configure per-request: moderation_api.content.submit(content: {text: "x", type: "text"}, request_options: {timeout: 5}) ``` -------------------------------- ### Manage Moderation Queue Items (Ruby) Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Interact with moderation queue items, including listing items with filters, resolving, and unresolving them. Requires a client object configured with API credentials. ```ruby items = client.queue.items.list( "queue_abc123", author_id: "user_12345", after_date: "2024-01-01", before_date: "2024-12-31", conversation_ids: "thread_abc,thread_xyz", labels: "toxic,spam" ) result = client.queue.items.resolve( "item_123", id: "queue_abc123", comment: "Reviewed and approved by moderator" ) result = client.queue.items.unresolve( "item_123", id: "queue_abc123", comment: "Needs additional review" ) ``` -------------------------------- ### Use Tagged Symbols for Enums in Ruby Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Illustrates using "tagged symbols" for enum-like constants in Ruby when Sorbet runtime is not a dependency. It shows accessing constants like `ModerationAPI::AuthorListParams::SortBy::TRUST_LEVEL` and reveals their type. ```ruby # :trustLevel puts(ModerationAPI::AuthorListParams::SortBy::TRUST_LEVEL) # Revealed type: `T.all(ModerationAPI::AuthorListParams::SortBy, Symbol)` T.reveal_type(ModerationAPI::AuthorListParams::SortBy::TRUST_LEVEL) ``` -------------------------------- ### Pass Enum Constants or Literal Values in Ruby Source: https://github.com/moderation-api/sdk-ruby/blob/main/README.md Shows the flexibility in passing enum values for parameters, allowing either the dedicated enum constants (preserving type information) or their literal string values. ```ruby # Using the enum constants preserves the tagged type information: moderation_api.authors.list( sort_by: ModerationAPI::AuthorListParams::SortBy::TRUST_LEVEL, # … ) # Literal values are also permissible: moderation_api.authors.list( sort_by: :trustLevel, # … ) ``` -------------------------------- ### Handle Moderation API Errors (Ruby) Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Implement robust error handling for various API responses, including authentication, rate limiting, bad requests, not found, network issues, timeouts, server errors, and general API errors. Uses specific exception classes from the ModerationAPI::Errors module. ```ruby begin response = client.content.submit( content: {text: "Test content", type: "text"} ) puts response.recommendation rescue ModerationAPI::Errors::AuthenticationError => e puts "Authentication failed: #{e.message}" puts "Status: #{e.status}" rescue ModerationAPI::Errors::RateLimitError => e puts "Rate limit exceeded: #{e.message}" puts "Retry after: #{e.headers['retry-after']}" rescue ModerationAPI::Errors::BadRequestError => e puts "Invalid request: #{e.message}" puts "Body: #{e.body}" rescue ModerationAPI::Errors::NotFoundError => e puts "Resource not found: #{e.url}" rescue ModerationAPI::Errors::APIConnectionError => e puts "Network error: #{e.message}" puts "Cause: #{e.cause}" rescue ModerationAPI::Errors::APITimeoutError => e puts "Request timed out: #{e.url}" rescue ModerationAPI::Errors::InternalServerError => e puts "Server error: #{e.status}" rescue ModerationAPI::Errors::APIStatusError => e puts "API error #{e.status}: #{e.message}" rescue ModerationAPI::Errors::APIError => e puts "General API error: #{e.message}" end ``` -------------------------------- ### Serialize Responses Source: https://context7.com/moderation-api/sdk-ruby/llms.txt Converts API response objects into various serialization formats such as JSON, YAML, or Ruby Hashes. This is useful for logging, debugging, or integrating with other systems that expect specific data formats. ```ruby # Serialize responses puts response.to_json puts response.to_yaml hash = response.to_h deep_hash = response.deep_to_h ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.