### Check Ruby Gem Installation and Dependencies Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Provides commands to verify the installation of the ToggleCraft gem and its dependencies using Bundler. Includes steps for checking, verifying, and reinstalling gems. ```bash # Check gem is installed gem list togglecraft # Verify dependencies bundle check # Reinstall if needed bundle install ``` -------------------------------- ### Profile Ruby Code with Ruby-Prof Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Demonstrates how to use the `ruby-prof` gem to profile Ruby code and identify CPU-intensive sections. The example starts profiling, runs a loop of flag evaluations, stops profiling, and prints the results using a FlatPrinter. ```ruby require 'ruby-prof' RubyProf.start # Your code here 1000.times { client.enabled?('feature', user: { id: '123' }) } result = RubyProf.stop printer = RubyProf::FlatPrinter.new(result) printer.print(STDOUT) ``` -------------------------------- ### Install ToggleCraft Ruby SDK Source: https://github.com/togglecraft/ruby-sdk/blob/main/README.md Instructions for adding the ToggleCraft Ruby SDK to your project's Gemfile or installing it directly via gem command. ```ruby gem 'togglecraft' ``` ```bash gem install togglecraft ``` -------------------------------- ### Profile Ruby Flag Evaluations with Benchmark Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Shows how to use Ruby's Benchmark module to measure the time taken for flag evaluations, helping to identify performance bottlenecks. The example benchmarks 1000 evaluations and calculates the average time in milliseconds, aiming for less than 1ms per evaluation. ```ruby require 'benchmark' time = Benchmark.realtime do 1000.times do client.enabled?('feature', user: { id: '123' }) end end avg_time = (time / 1000) * 1000 # Convert to ms puts "Average evaluation time: #{avg_time.round(2)}ms" # Should be < 1ms ``` -------------------------------- ### Minitest: Setup and Helpers for Feature Flag Testing Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/FRAMEWORKS.md This Minitest setup, placed in `test/test_helper.rb`, configures a mock ToggleCraft client for tests. It provides helper methods like `enable_feature`, `disable_feature`, and `set_variant` that define expectations on the mock client, simplifying the process of testing feature flag logic within Minitest. ```ruby # test/test_helper.rb class ActiveSupport::TestCase def setup # Mock togglecraft client @togglecraft_mock = Minitest::Mock.new Rails.application.config.togglecraft = @togglecraft_mock end def enable_feature(flag_key) @togglecraft_mock.expect(:enabled?, true, [flag_key, Hash]) end def disable_feature(flag_key) @togglecraft_mock.expect(:enabled?, false, [flag_key, Hash]) end def set_variant(flag_key, variant) @togglecraft_mock.expect(:variant, variant, [flag_key, Hash]) end def teardown @togglecraft_mock.verify end end # Usage class DashboardControllerTest < ActionDispatch::IntegrationTest test 'shows premium dashboard when flag enabled' enable_feature('premium-dashboard') get dashboard_url assert_response :success assert_select 'h1', 'Premium Dashboard' end test 'shows standard dashboard when flag disabled' disable_feature('premium-dashboard') get dashboard_url assert_response :success assert_select 'h1', 'Dashboard' end end ``` -------------------------------- ### Configure Reconnection Settings for ToggleCraft Client Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Provides an example of configuring reconnection intervals and maximum attempts for the ToggleCraft client. Adjusting these settings can help manage connection stability and avoid rate limiting. ```ruby client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], reconnect_interval: 2, # Start with 2 seconds max_reconnect_interval: 60, # Max 60 seconds max_reconnect_attempts: 20 # More attempts before slow mode ) ``` -------------------------------- ### Rails Gemfile Setup for ToggleCraft Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/FRAMEWORKS.md Adds the ToggleCraft SDK to your Rails application by including it in the Gemfile. Ensure you have the gem installed. ```ruby gem 'togglecraft' ``` -------------------------------- ### Check ToggleCraft Ruby SDK Version Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Prints the currently installed version of the ToggleCraft Ruby SDK to the console. It also includes a comment suggesting how to update the gem if necessary using Bundler. ```ruby puts "ToggleCraft version: #{ToggleCraft::VERSION}" # Update if needed bundle update togglecraft ``` -------------------------------- ### Handle :ready Event in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/API.md Example of registering an event listener for the :ready event, which fires once when the initial flags are loaded by the SDK. ```ruby # Ready event client.on(:ready) do puts 'Client ready, flags loaded' end ``` -------------------------------- ### Sinatra Setup with ToggleCraft SDK Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/FRAMEWORKS.md Initializes the ToggleCraft client within a Sinatra application, establishing a connection and making the client available via settings. Includes helper methods for checking feature flags and user context. ```ruby # app.rb require 'sinatra' require 'togglecraft' # Initialize client configure do set :togglecraft, ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], logger: Logger.new(STDOUT) ) settings.togglecraft.connect end # Helper methods helpers do def togglecraft settings.togglecraft end def feature_enabled?(flag_key, context = {}) togglecraft.enabled?(flag_key, context) end def current_user_context return {} unless session[:user_id] { user: { id: session[:user_id], email: session[:user_email] } } end end # Clean up on exit at_exit do settings.togglecraft.destroy end ``` -------------------------------- ### Test Ruby Gem Locally Source: https://github.com/togglecraft/ruby-sdk/blob/main/PUBLISHING.md This demonstrates installing a locally built Ruby gem and then testing its basic functionality within an IRB session. It requires the `togglecraft` gem to be installed locally before proceeding with tests. ```bash # Install locally to test gem install ./togglecraft-1.0.0.gem # Test in IRB irb require 'togglecraft' client = ToggleCraft::Client.new(sdk_key: 'test-key') # ... test basic functionality ``` -------------------------------- ### Modular Sinatra App Setup with ToggleCraft Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/FRAMEWORKS.md Shows how to integrate ToggleCraft into a modular Sinatra application structure, initializing the client within the `Sinatra::Base` subclass and providing access via a helper method. ```ruby # app.rb require 'sinatra/base' require 'togglecraft' class MyApp < Sinatra::Base configure do set :togglecraft, ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'] ) settings.togglecraft.connect end helpers do def togglecraft settings.togglecraft end end get '/' do if togglecraft.enabled?('new-homepage') erb :new_home else erb :home end end at_exit do settings.togglecraft&.destroy end end ``` -------------------------------- ### Integrate ToggleCraft with Sidekiq Workers Source: https://github.com/togglecraft/ruby-sdk/blob/main/README.md Provides an example of integrating ToggleCraft within a Sidekiq worker, including initializing the client, managing connections, and evaluating feature flags for background jobs. ```ruby class FeatureWorker include Sidekiq::Worker def togglecraft @togglecraft ||= ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], share_connection: true # Share connection with other workers ) end def perform(user_id) togglecraft.connect unless togglecraft.connected? if togglecraft.enabled?('batch-processing', user: { id: user_id }) # Use new batch processing end end end ``` -------------------------------- ### Handle Connection Errors and Ready State (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Listens for connection errors and the ready event from the ToggleCraft client. Emits connection status and the number of flags available when connected. ```ruby client.on(:error) do |error| puts "Connection error: #{error.message}" puts error.backtrace.join("\n") end client.on(:ready) do puts "Connected! Flags: #{client.all_flag_keys.length}" end ``` -------------------------------- ### Roda Application Setup with ToggleCraft Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/FRAMEWORKS.md Integrates ToggleCraft into a Roda application by initializing the client and storing it in the application's options. Helper methods are defined to access the client and user context within routes. ```ruby # app.rb require 'roda' require 'togglecraft' class App < Roda # Initialize ToggleCraft configure do |c| c[:togglecraft] = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'] ) c[:togglecraft].connect end plugin :render plugin :all_verbs # Helper method def togglecraft opts[:togglecraft] end def current_user_context return {} unless session['user_id'] { user: { id: session['user_id'], email: session['user_email'] } } end route do |r| r.root do if togglecraft.enabled?('new-homepage', current_user_context) view 'new_home' else view 'home' end end r.on 'dashboard' do variant = togglecraft.variant('dashboard-layout', current_user_context) case variant when 'compact' view 'dashboard_compact' when 'expanded' view 'dashboard_expanded' else view 'dashboard' end end end # Cleanup at_exit do opts[:togglecraft]&.destroy end end ``` -------------------------------- ### ToggleCraft Ruby SDK Client Initialization and Usage Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/API.md This comprehensive example demonstrates the full lifecycle of using the ToggleCraft Ruby SDK. It covers client initialization with various configurations, setting up event handlers, connecting to the service, defining user context, and evaluating feature flags and variants. ```ruby require 'togglecraft' # Initialize client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], enable_cache: true, cache_adapter: :memory, debug: false, logger: Logger.new(STDOUT) ) # Set up event handlers client.on(:ready) { puts 'Client ready!' } client.on(:error) { |e| puts "Error: #{e}" } client.on(:flags_updated) { |flags| puts "Updated: #{flags.keys}" } # Connect client.connect client.wait_for_ready # Define context context = { user: { id: '123', email: 'user@example.com', plan: 'premium' } } # Evaluate flags if client.enabled?('new-feature', context) puts 'Feature enabled!' end variant = client.variant('ab-test', context) puts "Variant: #{variant}" if client.in_percentage?('rollout', context) puts 'User is in rollout!' end # Clean up at_exit { client.destroy } ``` -------------------------------- ### Hanami Application Setup with ToggleCraft Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/FRAMEWORKS.md Configures the ToggleCraft client within a Hanami application's boot process, making it accessible globally through a module method. This allows feature flag checks within Hanami actions. ```ruby # config/boot.rb require 'togglecraft' Hanami.application.configure do before_load do @togglecraft = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], logger: Hanami.logger ) @togglecraft.connect end end # Make available to app module Togglecraft def self.client Hanami.application.instance_variable_get(:@togglecraft) end end ``` -------------------------------- ### Check Ruby Version Requirement Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Shows how to check the currently installed Ruby version. The ToggleCraft SDK requires Ruby version 3.0 or higher. ```bash ruby -v # Should be 3.0 or higher ``` -------------------------------- ### Enable Debug Mode in ToggleCraft Client Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Demonstrates how to enable debug mode for the ToggleCraft client to get detailed logging output, aiding in troubleshooting connection and flag loading issues. Requires specifying a logger, such as STDOUT. ```ruby client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], debug: true, # Enable detailed logging logger: Logger.new(STDOUT) ) ``` -------------------------------- ### Install CA Certificates in Docker for Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md A Dockerfile snippet that ensures CA certificates are installed in a Ruby 3.2 environment. This is crucial for establishing secure HTTPS connections, often required by SDKs like ToggleCraft when running in a containerized environment. ```dockerfile # Ensure CA certificates are installed FROM ruby:3.2 RUN apt-get update && apt-get install -y ca-certificates ``` -------------------------------- ### Verify SDK Key Environment Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Provides a Ruby script to determine the environment (development, staging, production) associated with a given ToggleCraft SDK key based on its prefix. ```ruby # Check which environment your key is for configuration_value = ENV['TOGGLECRAFT_SDK_KEY'] case configuration_value when /^tc_dev_/ puts 'Development environment' when /^tc_stg_/ puts 'Staging environment' when /^tc_live_/ puts 'Production environment' else puts 'Unknown environment!' end ``` -------------------------------- ### Minimize Context for Ruby Flag Evaluations Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Provides an example of reducing the context passed during flag evaluations to improve performance. It contrasts sending excessive user data (like a full JSON object) with sending only necessary attributes (ID and plan), which is crucial for faster evaluations. ```ruby # ❌ BAD - Huge context context = current_user.as_json # Too much data! # ✅ GOOD - Minimal context context = { user: { id: current_user.id, plan: current_user.plan } } ``` -------------------------------- ### Set TOGGLECRAFT_SDK_KEY in Kubernetes Deployment Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md An example Kubernetes YAML snippet demonstrating how to configure the `TOGGLECRAFT_SDK_KEY` environment variable within a deployment. The SDK key is sourced from a Kubernetes secret, ensuring secure handling of sensitive credentials. ```yaml # Ensure environment variable is set env: - name: TOGGLECRAFT_SDK_KEY valueFrom: secretKeyRef: name: togglecraft-secret key: sdk-key ``` -------------------------------- ### Wait for ToggleCraft Client Ready State Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Demonstrates how to ensure flags are loaded before evaluating them by using `client.wait_for_ready`. This is crucial for preventing default values from being returned due to flags not yet being available. ```ruby # Don't evaluate immediately client = ToggleCraft::Client.new(sdk_key: ENV['TOGGLECRAFT_SDK_KEY']) client.connect # Wait for flags to load client.wait_for_ready(timeout: 10) # Now flags should be loaded puts "Flag count: #{client.all_flag_keys.length}" puts "Flags: #{client.all_flag_keys.join(', ')}" ``` -------------------------------- ### Running Security Audits with bundler-audit Source: https://github.com/togglecraft/ruby-sdk/blob/main/SECURITY.md These commands demonstrate how to install and run the `bundler-audit` tool to check for security vulnerabilities in your project's dependencies. Ensure you update the vulnerability database before auditing. ```bash # Install bundler-audit gem install bundler-audit # Update vulnerability database bundle audit --update # Check for vulnerabilities bundle audit ``` -------------------------------- ### Build and Push Pre-release Ruby Gem Source: https://github.com/togglecraft/ruby-sdk/blob/main/PUBLISHING.md This bash command sequence builds the gem with a pre-release version and then pushes it to RubyGems. It also includes instructions for users on how to install pre-release versions using the `--pre` flag or by specifying the exact version in their Gemfile. ```bash # Build and push gem build togglecraft.gemspec gem push togglecraft-1.0.0.beta.1.gem # Users can install with: gem install togglecraft --pre # or in Gemfile: gem 'togglecraft', '1.0.0.beta.1' ``` -------------------------------- ### Handle Initialization Errors in Rails (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Implements robust initialization for the ToggleCraft client in Rails, including error handling. If initialization fails, it logs the error and sets up a null object to prevent downstream application failures. ```ruby # config/initializers/togglecraft.rb begin Rails.application.config.togglecraft = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], logger: Rails.logger ) Rails.application.config.togglecraft.connect rescue StandardError => e Rails.logger.error "Failed to initialize ToggleCraft: #{e.message}" # Provide a null object to prevent errors Rails.application.config.togglecraft = NullToggleCraftClient.new end ``` -------------------------------- ### Rails Initializer for ToggleCraft Client (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Configures and initializes the ToggleCraft client within a Rails application's initializer. It sets up the client with the SDK key, Rails logger, and debug mode based on the environment. ```ruby # config/initializers/togglecraft.rb Rails.application.config.togglecraft = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], logger: Rails.logger, debug: Rails.env.development? ) Rails.application.config.togglecraft.connect puts "ToggleCraft initialized with #{Rails.application.config.togglecraft.all_flag_keys.length} flags" ``` -------------------------------- ### Manually Test ToggleCraft Ruby SDK Connection Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Establishes a connection using the ToggleCraft client and listens for 'ready' and 'error' events. It then verifies the connection status, readiness, and lists all available feature flags. Requires the `togglecraft` gem and a valid SDK key. The connection is tested after a 5-second delay. ```ruby require 'togglecraft' client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], debug: true ) client.on(:ready) { puts 'READY!' } client.on(:error) { |e| puts "ERROR: #{e}" } client.connect sleep 5 puts "Connected: #{client.connected?}" puts "Ready: #{client.ready?}" puts "Flags: #{client.all_flag_keys.join(', ')}" ``` -------------------------------- ### Verify SDK Key and Network Connectivity Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Ensures the correct SDK key is used and verifies network access to ToggleCraft's SSE endpoint. Includes steps to check the SDK key format, test network connectivity with cURL and Ruby, and resolve DNS issues. ```ruby client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'] # Should start with 'tc_' ) # Verify it's set puts "SDK Key: #{ENV['TOGGLECRAFT_SDK_KEY']}" ``` ```bash # Test connection curl https://sse.togglecraft.io/health # Check DNS resolution nslookup sse.togglecraft.io ``` ```ruby require 'net/http' uri = URI('https://sse.togglecraft.io/health') response = Net::HTTP.get_response(uri) puts response.code ``` -------------------------------- ### Publish Ruby Gem to RubyGems Source: https://github.com/togglecraft/ruby-sdk/blob/main/PUBLISHING.md This bash command pushes the built Ruby gem file to the RubyGems.org repository, making it available for installation by others. The output confirms the successful registration of the gem. ```bash # Push to RubyGems gem push togglecraft-1.0.0.gem # Output: # Pushing gem to https://rubygems.org... # Successfully registered gem: togglecraft (1.0.0) ``` -------------------------------- ### Test SSL/TLS Connection with Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Includes a Ruby script to test the SSL/TLS connection to ToggleCraft's endpoint. This helps diagnose issues related to certificate verification and secure communication. ```ruby require 'openssl' require 'net/http' uri = URI('https://sse.togglecraft.io') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER begin http.start { |h| h.get('/') } puts 'SSL connection successful' rescue OpenSSL::SSL::SSLError => e puts "SSL error: #{e.message}" end ``` -------------------------------- ### Rakefile Tasks for Ruby SDK Source: https://github.com/togglecraft/ruby-sdk/blob/main/PUBLISHING.md Defines Rake tasks for testing, linting, security checks, and local installation of the Ruby SDK gem. It requires bundler, rspec, and rubocop gems. ```ruby require 'bundler/gem_tasks' require 'rspec/core/rake_task' require 'rubocop/rake_task' RSpec::Core::RakeTask.new(:spec) RuboCop::RakeTask.new desc 'Run all pre-publish checks' task :pre_publish do puts 'Running tests...' Rake::Task['spec'].invoke puts 'Running linter...' Rake::Task['rubocop'].invoke puts 'Checking for security issues...' system('bundle audit --update') puts 'All checks passed! ✓' end desc 'Build and install gem locally' task :install_local do version = ToggleCraft::VERSION system("gem build togglecraft.gemspec") system("gem install togglecraft-#{version}.gem") puts "Installed togglecraft-#{version} locally ✓" end task default: [:spec, :rubocop] ``` -------------------------------- ### Configure Client with Cache TTL (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Initializes the ToggleCraft client with caching enabled and a reduced Time-To-Live (TTL) for testing flag updates. This helps in observing changes more rapidly during development. ```ruby client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], enable_cache: true, cache_ttl: 60 # 1 minute for testing ) ``` -------------------------------- ### Handle Disconnected Events and Reconnection Logic Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Illustrates how to listen for disconnection events and implement reconnection logic using the ToggleCraft client's event callbacks. Includes handlers for `:disconnected`, `:reconnecting`, and `:ready` states. ```ruby client.on(:disconnected) do puts 'Disconnected - check network' end client.on(:reconnecting) do puts 'Attempting to reconnect...' end client.on(:ready) do puts 'Successfully reconnected' end ``` -------------------------------- ### Use Dotenv for SDK Key in Development (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Integrates the `dotenv-rails` gem to manage environment variables, specifically the ToggleCraft SDK key, in development and test environments. It demonstrates how to fetch the key and raise an error if it's missing. ```ruby # Gemfile gem 'dotenv-rails', groups: [:development, :test] # .env (add to .gitignore!) TOGGLECRAFT_SDK_KEY=tc_dev_abc123... # config/initializers/togglecraft.rb Rails.application.config.togglecraft = ToggleCraft::Client.new( sdk_key: ENV.fetch('TOGGLECRAFT_SDK_KEY') # Raises if missing ) ``` -------------------------------- ### Set SDK Key for ToggleCraft Client in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Illustrates how to correctly initialize the ToggleCraft::Client in Ruby, ensuring the SDK key is provided. It uses `ENV.fetch` to retrieve the key, which raises an error if the environment variable is not set, preventing the "SDK key is required" error. ```ruby # Ensure SDK key is set client = ToggleCraft::Client.new( sdk_key: ENV.fetch('TOGGLECRAFT_SDK_KEY') ) ``` -------------------------------- ### Evaluate Multivariate Feature Flags with ToggleCraft Source: https://github.com/togglecraft/ruby-sdk/blob/main/README.md Shows how to use the `variant` method to get different variations of a feature for A/B/n testing, allowing for multiple outcomes based on the flag's configuration. ```ruby variant = client.variant('checkout-flow', user: { id: '123' }) case variant when 'one-page' render_one_page_checkout when 'multi-step' render_multi_step_checkout else render_default_checkout end ``` -------------------------------- ### Separate ToggleCraft Client Per Worker in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Illustrates the best practice of using a separate ToggleCraft client instance for each worker to avoid potential concurrency issues and ensure proper connection management. Each worker creates its own client, sharing the connection if configured. ```ruby class MyWorker include Sidekiq::Worker def perform(user_id) # Each worker instance gets its own client client = togglecraft_client client.connect unless client.connected? if client.enabled?('feature', user: { id: user_id }) # ... end end private def togglecraft_client @client ||= ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], share_connection: true ) end end ``` -------------------------------- ### Rails Credentials Setup for SDK Key Source: https://github.com/togglecraft/ruby-sdk/blob/main/SECURITY.md Provides instructions for setting up and using Rails encrypted credentials to store the ToggleCraft SDK key securely. This method is recommended for production environments as it keeps secrets out of version control. ```bash # Edit credentials EDITOR=vim rails credentials:edit # Add to credentials togglecraft: sdk_key: tc_live_abc123... # Use in initializer sdk_key: Rails.application.credentials.togglecraft.sdk_key ``` -------------------------------- ### Adjust Initializer Load Order (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Demonstrates how to prepend a number to an initializer file name to control its loading order within a Rails application. This is useful if the ToggleCraft initializer depends on other configurations. ```ruby # config/initializers/01_togglecraft.rb # Loads first Rails.application.config.togglecraft = ToggleCraft::Client.new(...) ``` -------------------------------- ### Advanced Targeting with Context Evaluation - Ruby Source: https://context7.com/togglecraft/ruby-sdk/llms.txt Explains how to perform advanced targeting using context evaluation with ToggleCraft SDK. It highlights the availability of 14 operators for flexible rule creation and demonstrates examples of evaluating flags based on user attributes, request details, and device information. The SDK supports string, numeric, and semantic versioning operators, with support for AND/OR combinators. ```ruby # Targeting rules are evaluated server-side and cached locally # The SDK supports 14 operators for flexible targeting context = { user: { id: 'user-123', email: 'user@example.com', age: 25, plan: 'premium', role: 'admin', signup_date: '2024-01-15', version: '2.5.1' }, request: { country: 'US', ip: '192.168.1.1' }, device: { type: 'mobile', os: 'iOS' } } # The SDK evaluates locally using these operators: # String operators: equals, not_equals, contains, not_contains, starts_with, ends_with, in, not_in, regex # Numeric operators: gt, gte, lt, lte, between # Version operators: semver_eq, semver_gt, semver_gte, semver_lt, semver_lte # Example: Flag enabled for premium users in US is_premium_us = client.enabled?('premium-feature', context, default: false) # Example: Multivariate based on user age variant = client.variant('age-based-ui', context, default: 'standard') # Example: Rollout to users with specific app version in_rollout = client.in_percentage?('new-version-feature', context, default: false) # Rules support AND/OR combinators # Context properties accessed via dot notation: user.plan, request.country, device.type ``` -------------------------------- ### Initialize and Use ToggleCraft Client in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/README.md Demonstrates how to initialize the ToggleCraft client with an SDK key, connect to the service, wait for flags to be ready, and check if a feature is enabled for a given user. ```ruby require 'togglecraft' # Initialize client client = ToggleCraft::Client.new(sdk_key: 'your-sdk-key') # Connect and wait for flags client.connect client.wait_for_ready # Use your flags if client.enabled?('new-feature', user: { id: current_user.id }) # Feature is enabled end ``` -------------------------------- ### Securely Logging SDK Keys in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/SECURITY.md Illustrates the correct and incorrect ways to log sensitive information, specifically SDK keys, in Ruby. The example shows how to mask or avoid logging the SDK key entirely to prevent accidental exposure. ```ruby # BAD - Logs SDK key logger.info "Connecting with key: #{sdk_key}" ``` ```ruby # GOOD - Mask SDK key masked_key = "#{sdk_key[0..10]}***" logger.info "Connecting with key: #{masked_key}" # GOOD - Don't log key at all logger.info "Connecting to ToggleCraft" ``` -------------------------------- ### Configure ToggleCraft Client with Caching in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Demonstrates how to initialize the ToggleCraft::Client with caching enabled in Ruby. This snippet shows setting `enable_cache` to true (which is the default) and configuring the `cache_ttl` (time-to-live) for cached flag evaluations. ```ruby client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], enable_cache: true, # Should be enabled (default) cache_ttl: 300 ) ``` -------------------------------- ### Inspect Internal State of ToggleCraft Ruby SDK Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Provides a way to inspect the internal state of the ToggleCraft client for debugging purposes. This includes the current version, connection status, and cache keys. Note that these are internal APIs and may change without notice. ```ruby # For debugging only - internal APIs may change puts "Current version: #{client.instance_variable_get(:@current_version).value}" puts "Connection state: #{client.instance_variable_get(:@connection)}" puts "Cache keys: #{client.instance_variable_get(:@cache)&.keys}" ``` -------------------------------- ### Error Handling and Best Practices Source: https://github.com/togglecraft/ruby-sdk/blob/main/README.md Guidance on handling connection errors, initializing the client, and managing application shutdown. ```APIDOC ## Best Practices & Error Handling ### Initialize Once Create a single client instance and reuse it throughout your application's lifecycle. ### Always Provide Context Include attributes like `user.id` in the context for consistent flag evaluation. ### Use Default Values Provide default values for flags to ensure graceful handling when flags are missing or errors occur. ### Clean Up on Shutdown Ensure `client.destroy` is called when your application is shutting down to release resources. ```ruby # Example of handling connection errors and application shutdown: at_exit do client.destroy end begin client.connect rescue StandardError => e logger.error "Failed to connect: #{e}" # Application continues with cached values or defaults end ``` ``` -------------------------------- ### Enable Verbose Logging in ToggleCraft Ruby SDK Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Configures the ToggleCraft client to use a logger that outputs debug-level messages to standard output. This is useful for diagnosing issues by providing detailed information about the SDK's operations. Requires the `togglecraft` gem. ```ruby logger = Logger.new(STDOUT) logger.level = Logger::DEBUG client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], debug: true, logger: logger ) ``` -------------------------------- ### Configure Shared Connection in Rails (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Sets up the ToggleCraft client in a Rails initializer to share a single connection across threads using `share_connection: true`. This is beneficial for multi-process environments like Puma to avoid redundant connections. ```ruby # config/initializers/togglecraft.rb Rails.application.config.togglecraft = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], share_connection: true # Share connection across threads ) ``` -------------------------------- ### Graceful Degradation and Error Recovery - Ruby Source: https://context7.com/togglecraft/ruby-sdk/llms.txt Details how to implement error handling and resilience with the ToggleCraft Ruby SDK. It shows how to gracefully degrade application functionality by using default flag values or continuing without feature flags when initialization or connection attempts fail. Examples include handling `Timeout::Error` during `wait_for_ready` and general `StandardError` during client initialization. ```ruby # Initialize with error handling begin client = ToggleCraft::Client.new(sdk_key: ENV['TOGGLECRAFT_SDK_KEY']) client.connect # Wait for ready with timeout client.wait_for_ready(timeout: 5) rescue Timeout::Error puts "Timed out waiting for flags - will use defaults" # Application continues with default flag values rescue StandardError => e puts "Failed to initialize ToggleCraft: #{e.message}" # Application continues without feature flags end ``` -------------------------------- ### Manage ToggleCraft Connection Pooling in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Demonstrates how to enable connection pooling and manage connections within the ToggleCraft Ruby SDK to resolve 'Too many connections' errors. It shows setting `share_connection: true` to reuse connections and provides a command to clear the pool forcefully. ```ruby # Enable connection pooling client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], share_connection: true # Reuse connections ) # Or clean up old connections ToggleCraft::ConnectionPool.clear(force: true) ``` -------------------------------- ### Configure ToggleCraft Client Options Source: https://github.com/togglecraft/ruby-sdk/blob/main/README.md Details various optional parameters for initializing the ToggleCraft client, including SDK key, caching options (enable, adapter, TTL), and debug logging. ```ruby client = ToggleCraft::Client.new( # Required sdk_key: 'your-sdk-key', # Get from ToggleCraft dashboard # Optional - Common settings enable_cache: true, # Enable caching (default: true) cache_adapter: :memory, # :memory or :redis (default: :memory) cache_ttl: 300, # Cache TTL in seconds (default: 5 minutes) debug: false # Enable debug logging (default: false) ) ``` -------------------------------- ### ToggleCraft SDK Evaluation Caching Example Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/ADVANCED.md Demonstrates the effect of evaluation caching in the ToggleCraft SDK. The first call to 'enabled?' performs rule evaluation, while subsequent calls within the cache TTL are served from the cache, resulting in significantly faster execution times. ```ruby # First evaluation - computes rules client.enabled?('feature', user: { id: '123' }) # ~0.5ms # Subsequent evaluations within cache TTL - cached client.enabled?('feature', user: { id: '123' }) # ~0.01ms ``` -------------------------------- ### Handle Blocking Operations in Ruby Event Handlers Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Provides a solution for 'Thread deadlock detected' errors by ensuring that event handlers do not perform blocking operations. The example shows replacing a blocking `sleep` with an asynchronous job execution using `perform_async`. ```ruby # Don't block in event handlers client.on(:flags_updated) do |flags| # ❌ Don't do this # sleep 10 # expensive_operation # ✅ Do this ProcessFlagsJob.perform_async(flags.to_json) end ``` -------------------------------- ### Client Configuration Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/API.md Details on how to initialize and configure the ToggleCraft::Client with various options for SDK key, caching, connection, and debugging. ```APIDOC ## Client Configuration ### `ToggleCraft::Client.new(config)` Create a new ToggleCraft client instance. ```ruby client = ToggleCraft::Client.new(config) ``` #### Configuration Options | Option | Type | Default | Description | |------------------------------|---------|----------------|---------------------------------------------------| | `sdk_key` | String | **required** | Your SDK key from ToggleCraft dashboard | | `enable_cache` | Boolean | `true` | Enable flag caching | | `cache_adapter` | Symbol | `:memory` | Cache adapter: `:memory` or `:redis` | | `cache_ttl` | Integer | `300` | Cache TTL in seconds (5 minutes) | | `reconnect_interval` | Integer | `1` | Initial reconnect interval in seconds | | `max_reconnect_interval` | Integer | `30` | Maximum reconnect interval for exponential backoff | | `max_reconnect_attempts` | Integer | `10` | Max fast reconnection attempts before slow mode | | `slow_reconnect_interval` | Integer | `60` | Slow reconnection interval after max attempts | | `share_connection` | Boolean | `true` | Share SSE connections between instances | | `connection_pool_key` | String | `nil` | Custom connection pool key (advanced use only) | | `enable_rollout_stage_polling` | Boolean | `true` | Enable automatic rollout stage checking | | `rollout_stage_check_interval` | Integer | `60` | Interval for checking rollout stages in seconds | | `fetch_jitter` | Integer | `1500` | Maximum jitter in milliseconds for fetch requests | | `debug` | Boolean | `false` | Enable debug logging | | `logger` | Logger | `Logger.new(STDOUT)` | Logger instance | #### Example ```ruby client = ToggleCraft::Client.new( # Required sdk_key: 'your-sdk-key', # Optional - Caching enable_cache: true, cache_adapter: :memory, cache_ttl: 300, # Optional - Connection reconnect_interval: 1, max_reconnect_interval: 30, share_connection: true, # Optional - Debugging debug: true, logger: Rails.logger ) ``` ``` -------------------------------- ### Monitor ToggleCraft Connection Pool Stats in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Provides a Ruby code snippet to inspect the statistics of the ToggleCraft connection pool. It retrieves and prints the number of active connections and clients, which should ideally match the expected number of clients to detect potential leaks. ```ruby # Check for leaked connections stats = ToggleCraft::ConnectionPool.stats puts "Connections: #{stats[:connection_count]}" puts "Clients: #{stats[:client_count]}" # Should match expected number of clients ``` -------------------------------- ### Configure Evaluation Caching for ToggleCraft in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Explains how to configure the evaluation cache TTL in the ToggleCraft Ruby client to address 'Concurrent::Map full' errors, which can occur with too many flags or cache entries. This example reduces the TTL to 60 seconds. ```ruby # Reduce cache TTL client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], cache_ttl: 60 # Shorter TTL ) # Or disable evaluation caching # (not recommended, contact support) ``` -------------------------------- ### Initialize ToggleCraft Client (Ruby) Source: https://context7.com/togglecraft/ruby-sdk/llms.txt Initializes the ToggleCraft client with an SDK key and optional configuration parameters such as cache settings, reconnection intervals, and debug mode. It also shows how to connect to the SSE server and verify connection status. ```ruby require 'togglecraft' # Basic initialization client = ToggleCraft::Client.new(sdk_key: 'your-sdk-key-here') # Initialize with configuration options client = ToggleCraft::Client.new( sdk_key: 'your-sdk-key-here', enable_cache: true, cache_adapter: :memory, cache_ttl: 300, reconnect_interval: 1, max_reconnect_interval: 30, max_reconnect_attempts: 10, slow_reconnect_interval: 60, debug: false, enable_rollout_stage_polling: true, rollout_stage_check_interval: 60 ) # Connect to SSE server and wait for ready client.connect client.wait_for_ready(timeout: 5) # Check connection status puts "Connected: #{client.connected?}" puts "Ready: #{client.ready?}" ``` -------------------------------- ### Configure Rollout Stage Polling Interval in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Shows how to configure the polling interval for rollout stage checks in the ToggleCraft Ruby client. This helps reduce high CPU usage by decreasing the frequency of these checks, setting the interval to 5 minutes (300 seconds) in this example. ```ruby # Reduce polling frequency client = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], rollout_stage_check_interval: 300 # Check every 5 minutes ) ``` -------------------------------- ### Handle :reconnecting Event in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/API.md Example of registering an event listener for the :reconnecting event. This event fires when the SDK attempts to re-establish its connection to the ToggleCraft service. ```ruby # Reconnecting event client.on(:reconnecting) do puts 'Attempting to reconnect...' end ``` -------------------------------- ### Manually Clear Cache (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Provides a method to manually clear the ToggleCraft client's cache. This is intended for testing purposes only and should not be used in production environments. ```ruby # Force cache clear (for testing only) client.instance_variable_get(:'@cache').clear if client.instance_variable_defined?(:'@cache') ``` -------------------------------- ### Rails: Best Practice for ToggleCraft Client Initialization Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/FRAMEWORKS.md This code snippet illustrates the recommended best practice for initializing the ToggleCraft client in a Rails application. It emphasizes creating a single instance of the client and assigning it to `Rails.application.config.togglecraft` during application configuration to ensure consistent access and avoid redundant initializations. ```ruby # ✅ GOOD - Single instance Rails.application.config.togglecraft = ToggleCraft::Client.new(...) ``` -------------------------------- ### Verify SSE Connection Status (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Checks the current connection status of the ToggleCraft client and listens for disconnection events. Useful for debugging real-time updates. ```ruby puts "Connected: #{client.connected?}" puts "Ready: #{client.ready?}" client.on(:disconnected) do puts 'SSE connection lost!' end ``` -------------------------------- ### Listen for Flag Updates (Ruby) Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/TROUBLESHOOTING.md Subscribes to the `:flags_updated` event to receive notifications when feature flags change. Includes a placeholder for refreshing the UI or re-evaluating flag states. ```ruby client.on(:flags_updated) do |flags| puts "Flags updated at #{Time.now}" puts "Updated flags: #{flags.keys.join(', ')}" # Refresh UI or re-evaluate broadcast_flag_update(flags) end ``` -------------------------------- ### Configure ToggleCraft Client in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/API.md Instantiate the ToggleCraft client with various configuration options. Supports SDK key, caching, connection settings, and debugging. ```ruby client = ToggleCraft::Client.new( # Required sdk_key: 'your-sdk-key', # Optional - Caching enable_cache: true, cache_adapter: :memory, cache_ttl: 300, # Optional - Connection reconnect_interval: 1, max_reconnect_interval: 30, share_connection: true, # Optional - Debugging debug: true, logger: Rails.logger ) ``` -------------------------------- ### Configure ToggleCraft Client in Rails Application Source: https://github.com/togglecraft/ruby-sdk/blob/main/README.md Shows how to configure the ToggleCraft client as an initializer in a Rails application, setting the SDK key, cache adapter, logger, and debug mode. It also demonstrates connecting the client and ensuring it's destroyed at exit. ```ruby # config/initializers/togglecraft.rb Rails.application.config.togglecraft = ToggleCraft::Client.new( sdk_key: ENV['TOGGLECRAFT_SDK_KEY'], cache_adapter: :memory, logger: Rails.logger, debug: Rails.env.development? ) Rails.application.config.togglecraft.connect at_exit do Rails.application.config.togglecraft.destroy end ``` -------------------------------- ### Configure ToggleCraft SDK with Advanced Options Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/ADVANCED.md Demonstrates how to initialize the ToggleCraft::Client with a comprehensive set of advanced configuration options. This includes settings for caching, reconnection intervals, connection pooling, rollout stage polling, server URLs, and debugging. ```ruby client = ToggleCraft::Client.new( # ===== Required ===== sdk_key: 'your-sdk-key', # ===== Caching ===== enable_cache: true, # Enable/disable caching cache_adapter: :memory, # :memory or :redis cache_ttl: 300, # Cache time-to-live in seconds (5 minutes) # ===== Reconnection ===== reconnect_interval: 1, # Initial reconnect interval in seconds max_reconnect_interval: 30, # Max interval during exponential backoff (30 seconds) max_reconnect_attempts: 10, # Fast attempts before switching to slow mode slow_reconnect_interval: 60, # Slow reconnection interval (60 seconds) # ===== Connection Pooling ===== share_connection: true, # Share SSE connections between instances connection_pool_key: nil, # Custom pool key (advanced) # ===== Rollout Stage Polling ===== enable_rollout_stage_polling: true, # Enable automatic stage detection rollout_stage_check_interval: 60, # Check interval in seconds fetch_jitter: 1500, # Max jitter for fetch requests in milliseconds # ===== Server Configuration ===== url: 'https://sse.togglecraft.io', # SSE server URL api_domain: nil, # Custom API domain (for staging/dev) heartbeat_domain: nil, # Custom heartbeat domain (for staging/dev) # ===== Debugging ===== debug: false, # Enable debug logging logger: Logger.new(STDOUT) # Custom logger instance ) ``` -------------------------------- ### Handle :error Event in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/API.md Example of registering an event listener for the :error event. This event fires when an error occurs within the SDK, providing the error object and its backtrace. ```ruby # Error event client.on(:error) do |error| logger.error "ToggleCraft error: #{error.message}" logger.error error.backtrace.join("\n") end ``` -------------------------------- ### Handle :rollout_stage_changed Event in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/API.md Example of registering an event listener for the :rollout_stage_changed event. This event fires when a scheduled rollout stage becomes active, providing details about the change. ```ruby # Rollout stage changed event client.on(:rollout_stage_changed) do |data| puts "Rollout stage changed at #{data[:timestamp]}" data[:flags].each do |flag_data| puts "#{flag_data[:key]}: #{flag_data[:old_percentage]}% → #{flag_data[:new_percentage]}%" end end ``` -------------------------------- ### Handle :flags_updated Event in Ruby Source: https://github.com/togglecraft/ruby-sdk/blob/main/docs/API.md Example of registering an event listener for the :flags_updated event. This event fires when any flags managed by the SDK change, providing the updated flags hash. ```ruby # Flags updated event client.on(:flags_updated) do |flags| puts "Updated flags: #{flags.keys.join(', ')}" # Refresh UI or re-evaluate flags end ```