### Complete Application Example with TTY-Config and Optparse Source: https://context7.com/piotrmurach/tty-config/llms.txt This comprehensive example illustrates integrating TTY-Config with the `optparse` gem to build a command-line application. It showcases setting configuration paths, loading from environment variables, defining defaults, adding validation rules, parsing command-line arguments, and merging configurations from various sources. ```ruby require "tty-config" require "optparse" class App attr_reader :config def initialize @config = TTY::Config.new @config.filename = "myapp" @config.append_path(Dir.pwd) @config.append_path(File.join(Dir.home, ".config", "myapp")) @config.append_path("/etc/myapp") # Set up environment variable loading @config.env_prefix = "myapp" @config.autoload_env # Set defaults @config.set_if_empty(:host, value: "localhost") @config.set_if_empty(:port, value: 8080) @config.set_if_empty(:debug, value: false) # Add validation @config.validate(:port) do |key, value| unless value.to_i.between?(1, 65535) raise TTY::Config::ValidationError, "Invalid port: #{value}" end end end def load_config_file if @config.exist? @config.read puts "Loaded config from: #{@config.source_file}" end rescue TTY::Config::ReadError => e warn "Warning: #{e.message}" end def parse_options(argv) options = {} OptionParser.new do |opts| opts.banner = "Usage: myapp [options]" opts.on("-h", "--host HOST", "Server host") do |h| options[:host] = h end opts.on("-p", "--port PORT", Integer, "Server port") do |p| options[:port] = p end opts.on("-d", "--debug", "Enable debug mode") do options[:debug] = true end opts.on("-c", "--config FILE", "Config file path") do |c| options[:config_file] = c end end.parse!(argv) # Merge CLI options (highest priority) @config.merge(options) end def run puts "Starting server on #{@config.fetch(:host)}:#{@config.fetch(:port)}" puts "Debug mode: #{@config.fetch(:debug)}" end end # Usage: # MYAPP_HOST=production.example.com ruby app.rb --port 3000 --debug app = App.new app.load_config_file app.parse_options(ARGV) app.run ``` -------------------------------- ### Configure application with TTY::Config Source: https://github.com/piotrmurach/tty-config/blob/master/README.md An example of setting up an application's configuration using TTY::Config. It specifies the filename, file extension, and search paths for configuration files. ```ruby class App attr_reader :config def initialize @config = TTY::Config.new @config.filename = "investments" @config.extname = ".toml" @config.append_path Dir.pwd @config.append_path Dir.home end def self.config @config ||= self.class.new.config end end ``` -------------------------------- ### Install TTY::Config gem Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Instructions for installing the TTY::Config gem using Bundler or as a standalone gem. This makes the configuration library available in your Ruby project. ```ruby gem "tty-config" # Then execute: # $ bundle # Or install it yourself as: # $ gem install tty-config ``` -------------------------------- ### Working with Environment Variables in TTY::Config (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Provides examples of how TTY::Config integrates with environment variables. It shows setting environment variables, configuring TTY::Config to read them using `env_prefix` and `set_from_env` or `autoload_env`, and then fetching the values. ```ruby ENV["MYTOOL_HOST"] = "192.168.1.17" ENV["MYTOOL_PORT"] = "7727" config.env_prefix = "mytool" config.set_from_env(:host) config.set_from_env(:port) # Alternatively, using autoload_env: # config.autoload_env config.fetch(:host) # => "192.168.1.17" config.fetch(:port) # => "7727" ``` -------------------------------- ### Unregistering Marshallers in TTY-Config Source: https://context7.com/piotrmurach/tty-config/llms.txt This example shows how to remove marshallers from TTY-Config's registry, effectively disabling support for specific configuration file formats. It demonstrates unregistering multiple formats at once and the error handling that occurs when attempting to use a disabled format. ```ruby config = TTY::Config.new # Disable specific formats config.unregister_marshaller(:toml, :hcl, :xml) # Disable all but YAML and JSON config.unregister_marshaller(:toml, :ini, :xml, :hcl, :jprops) # Attempting to use disabled format raises error begin config.extname = ".toml" rescue TTY::Config::UnsupportedExtError => e puts e.message # => "Config file format `.toml` is not supported." end ``` -------------------------------- ### Initialize TTY::Config Instance Source: https://context7.com/piotrmurach/tty-config/llms.txt Demonstrates how to create a new TTY::Config instance with different initialization methods: basic, with initial settings, and using a block for configuration. ```ruby require "tty-config" # Basic initialization config = TTY::Config.new # With initial settings hash config = TTY::Config.new(settings: { base: "USD" }) # With block configuration config = TTY::Config.new do |c| c.filename = "myapp" c.extname = ".toml" c.append_path Dir.pwd c.append_path Dir.home end ``` -------------------------------- ### TTY::Config Initialization Source: https://context7.com/piotrmurach/tty-config/llms.txt Demonstrates how to create a new TTY::Config instance with various initialization options. ```APIDOC ## TTY::Config Initialization ### Description Creates a new configuration instance with optional initial settings and block configuration. ### Method `TTY::Config.new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby require "tty-config" # Basic initialization config = TTY::Config.new # With initial settings hash config = TTY::Config.new(settings: { base: "USD" }) # With block configuration config = TTY::Config.new do |c| c.filename = "myapp" c.extname = ".toml" c.append_path Dir.pwd c.append_path Dir.home end ``` ### Response #### Success Response (200) Returns a new `TTY::Config` object. #### Response Example (No specific response body, returns an object instance) ``` -------------------------------- ### Setting Configuration Values Source: https://context7.com/piotrmurach/tty-config/llms.txt Explains how to set configuration values using `set` for direct assignment, nested keys, and lazy evaluation. ```APIDOC ## POST /config/set ### Description Sets a value for a configuration key. Supports deeply nested keys using either multiple arguments or dot notation. Values can be provided directly or via a lazy-evaluated block. ### Method `set(key, **options)` or `set(*keys, **options)` ### Endpoint N/A (This is a method call, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (Symbol or String) - The key or sequence of keys for the configuration setting. - **value** (Any) - The value to set for the key. Can be a direct value or a block. ### Request Example ```ruby config = TTY::Config.new # Simple key-value config.set(:api_key, value: "abc123") # Deeply nested keys with multiple arguments config.set(:database, :primary, :host, value: "localhost") config.set(:database, :primary, :port, value: 5432) # Dot notation for nested keys config.set("database.replica.host", value: "replica.example.com") # Lazy evaluation with block (evaluated each time value is fetched) config.set(:timestamp) { Time.now.to_i } # Current configuration config.to_h # => {"api_key"=>"abc123", # "database"=>{"primary"=>{"host"=>"localhost", "port"=>5432}, # "replica"=>{"host"=>"replica.example.com"}}, # "timestamp"=>#} ``` ### Response #### Success Response (200) Returns the configuration object for chaining. #### Response Example (No specific response body, returns the config object ``` -------------------------------- ### Fetching Configuration Values Source: https://context7.com/piotrmurach/tty-config/llms.txt Details how to retrieve configuration values using `fetch`, including support for nested keys, default values, and indifferent access. ```APIDOC ## GET /config/fetch ### Description Retrieves a value for a configuration key with support for nested keys, defaults, and indifferent access (symbols/strings). ### Method `fetch(key, **options)` or `fetch(*keys, **options)` ### Endpoint N/A (This is a method call, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (Symbol or String) - The key or sequence of keys for the configuration setting to fetch. - **default** (Any) - A default value to return if the key is not found. - **block** (Proc) - A block that is evaluated to provide a default value if the key is not found. ### Request Example ```ruby config = TTY::Config.new config.set(:settings, :base, value: "USD") config.set(:settings, :color, value: true) config.set(:coins, value: ["BTC", "ETH", "TRX"]) # Simple fetch config.fetch(:coins) # => ["BTC", "ETH", "TRX"] # Nested key fetch (multiple arguments) config.fetch(:settings, :base) # => "USD" # Dot notation for nested keys config.fetch("settings.color") # => true # Indifferent access (mix symbols and strings) config.fetch("settings", :base) # => "USD" config.fetch(:settings, "color") # => true # With default value config.fetch(:missing_key, default: "fallback") # => "fallback" # With block default (lazy evaluated) config.fetch(:missing_key) { "computed_" + rand(100).to_s } # => "computed_42" ``` ### Response #### Success Response (200) Returns the value associated with the key, or a default value if specified and the key is not found. #### Response Example (Returns the fetched value, e.g., `"USD"` or `["BTC", "ETH", "TRX"]`) ``` -------------------------------- ### Binding Configuration to Environment Variables Source: https://context7.com/piotrmurach/tty-config/llms.txt Shows how to bind configuration keys to environment variables using `set_from_env` for dynamic value loading. ```APIDOC ## POST /config/set_from_env ### Description Binds a configuration key to an environment variable. The environment variable value is read dynamically each time the key is fetched. ### Method `set_from_env(key, **options)` or `set_from_env(*keys, **options)` ### Endpoint N/A (This is a method call, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (Symbol or String) - The configuration key to bind. - **block** (Proc) - Optional block to specify a custom environment variable name. ### Request Example ```ruby # Set up environment variables ENV["HOST"] = "192.168.1.17" ENV["PORT"] = "7727" ENV["MYAPP_DATABASE_URL"] = "postgres://localhost/mydb" config = TTY::Config.new # Direct binding (key name matches env var name) config.set_from_env(:host) config.set_from_env(:port) # Custom env var name mapping config.set_from_env(:db_url) { "MYAPP_DATABASE_URL" } # Nested key binding config.set_from_env(:database, :connection_string) { "MYAPP_DATABASE_URL" } config.fetch(:host) # => "192.168.1.17" config.fetch(:port) # => "7727" config.fetch(:db_url) # => "postgres://localhost/mydb" config.fetch(:database, :connection_string) # => "postgres://localhost/mydb" ``` ### Response #### Success Response (200) Returns the configuration object for chaining. #### Response Example (No specific response body, returns the config object) ``` -------------------------------- ### Bind Configuration Keys to Environment Variables Source: https://context7.com/piotrmurach/tty-config/llms.txt Demonstrates how to bind configuration keys to environment variables using `set_from_env`. Values are dynamically read upon fetching, and custom environment variable names can be mapped. ```ruby # Set up environment variables ENV["HOST"] = "192.168.1.17" ENV["PORT"] = "7727" ENV["MYAPP_DATABASE_URL"] = "postgres://localhost/mydb" config = TTY::Config.new # Direct binding (key name matches env var name) config.set_from_env(:host) config.set_from_env(:port) # Custom env var name mapping config.set_from_env(:db_url) { "MYAPP_DATABASE_URL" } # Nested key binding config.set_from_env(:database, :connection_string) { "MYAPP_DATABASE_URL" } config.fetch(:host) # => "192.168.1.17" config.fetch(:port) # => "7727" config.fetch(:db_url) # => "postgres://localhost/mydb" config.fetch(:database, :connection_string) # => "postgres://localhost/mydb" ``` -------------------------------- ### Setting Configuration Values If Empty Source: https://context7.com/piotrmurach/tty-config/llms.txt Demonstrates using `set_if_empty` to set a value only if the key is not already present, useful for defaults. ```APIDOC ## POST /config/set_if_empty ### Description Sets a value only if the key doesn't already have a value. Useful for providing defaults without overwriting existing configuration. ### Method `set_if_empty(key, **options)` or `set_if_empty(*keys, **options)` ### Endpoint N/A (This is a method call, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (Symbol or String) - The key or sequence of keys for the configuration setting. - **value** (Any) - The value to set for the key if it's empty. ### Request Example ```ruby config = TTY::Config.new # Set initial value config.set(:theme, value: "dark") # Attempt to set again - will NOT overwrite config.set_if_empty(:theme, value: "light") # Set a new key - will set since it's empty config.set_if_empty(:language, value: "en") config.fetch(:theme) # => "dark" (original value preserved) config.fetch(:language) # => "en" (new value set) ``` ### Response #### Success Response (200) Returns the configuration object for chaining. #### Response Example (No specific response body, returns the config object) ``` -------------------------------- ### Set and append configuration values Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Demonstrates how to set individual configuration values for nested keys and append values to array-type settings. This allows for structured and dynamic configuration. ```ruby config.set(:settings, :base, value: "USD") config.set(:settings, :color, value: true) config.set(:coins, value: ["BTC"]) config.append("ETH", "TRX", "DASH", to: :coins) ``` -------------------------------- ### Initialize and Configure TTY::Config Source: https://github.com/piotrmurach/tty-config/blob/master/README.md This section details the initialization of a TTY::Config object, setting the configuration filename, and specifying directories to search for configuration files. It also includes error handling for reading the configuration file. ```ruby config = TTY::Config.new config_filename = options[:config_file_path] || "config.yml" config.append_path Dir.pwd config.append_path Dir.home begin config.read(config_filename) rescue TTY::Config::ReadError => read_error STDERR.puts "\nNo configuration file found:" STDERR.puts read_error end ``` -------------------------------- ### Set Configuration Values with TTY::Config Source: https://context7.com/piotrmurach/tty-config/llms.txt Shows how to set configuration values using `set`, supporting simple key-value pairs, deeply nested keys via multiple arguments or dot notation, and lazy evaluation using blocks. ```ruby config = TTY::Config.new # Simple key-value config.set(:api_key, value: "abc123") # Deeply nested keys with multiple arguments config.set(:database, :primary, :host, value: "localhost") config.set(:database, :primary, :port, value: 5432) # Dot notation for nested keys config.set("database.replica.host", value: "replica.example.com") # Lazy evaluation with block (evaluated each time value is fetched) config.set(:timestamp) { Time.now.to_i } # Current configuration config.to_h # => {"api_key"=>"abc123", # "database"=>{"primary"=>{"host"=>"localhost", "port"=>5432}, # "replica"=>{"host"=>"replica.example.com"}}, # "timestamp"=>#} ``` -------------------------------- ### Writing Configuration Source: https://context7.com/piotrmurach/tty-config/llms.txt Writes current configuration to a file with options for overwriting and creating directories. ```APIDOC ## write ### Description Writes current configuration to a file with options for overwriting and creating directories. ### Method Write Configuration ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby config = TTY::Config.new config.filename = "investments" config.extname = ".yml" config.append_path(Dir.pwd) config.set(:settings, :base, value: "USD") config.set(:settings, :color, value: true) config.set(:coins, value: ["BTC", "ETH", "TRX"]) # Write to default location (current directory) config.write # Write with force overwrite config.write(force: true) # Write to custom path, creating directories if needed config.write("/custom/path/to/investments.toml", create: true, force: true) # Write to custom directory with current filename config.write(path: "/etc/myapp", create: true, force: true) # Output file (investments.yml): # --- # settings: # base: USD # color: true # coins: # - BTC # - ETH # - TRX ``` ### Response #### Success Response (200) Writes the configuration to the specified file. Returns `true` on success. #### Response Example ```ruby # => true ``` ``` -------------------------------- ### Fetch Configuration Values with TTY::Config Source: https://context7.com/piotrmurach/tty-config/llms.txt Explains how to retrieve configuration values using `fetch`, supporting nested keys, default values, lazy block defaults, and indifferent access (symbols/strings). ```ruby config = TTY::Config.new config.set(:settings, :base, value: "USD") config.set(:settings, :color, value: true) config.set(:coins, value: ["BTC", "ETH", "TRX"]) # Simple fetch config.fetch(:coins) # => ["BTC", "ETH", "TRX"] # Nested key fetch (multiple arguments) config.fetch(:settings, :base) # => "USD" # Dot notation for nested keys config.fetch("settings.color") # => true # Indifferent access (mix symbols and strings) config.fetch("settings", :base) # => "USD" config.fetch(:settings, "color") # => true # With default value config.fetch(:missing_key, default: "fallback") # => "fallback" # With block default (lazy evaluated) config.fetch(:missing_key) { "computed_#{rand(100)}" } # => "computed_42" ``` -------------------------------- ### Fetch configuration values Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Shows how to retrieve configuration values using nested keys. This method allows accessing specific settings within the configuration object. ```ruby config.fetch(:settings, :base) # => "USD" config.fetch(:coins) # => ["BTC", "ETH", "TRX", "DASH"] ``` -------------------------------- ### Merge Options and Validate Configuration Source: https://github.com/piotrmurach/tty-config/blob/master/README.md This code demonstrates merging the parsed command-line options with the configuration loaded from a file using `tty-config`. It concludes with a validation step to ensure that essential parameters like 'host' and 'port' are present in the final configuration. ```ruby config.merge(options) if !config.fetch(:host) || !config.fetch(:port) STDERR.puts "Host and port have to be specified (call with --help for help)." exit 1 end ``` -------------------------------- ### Create Aliases for TTY::Config Keys Source: https://context7.com/piotrmurach/tty-config/llms.txt Demonstrates the `alias_setting` method, which allows creating alternative names (aliases) for existing configuration keys. This facilitates accessing configuration values through different key names, including nested keys. ```ruby config = TTY::Config.new config.set(:base_currency, value: "USD") config.set(:settings, :primary_color, value: "#FF5733") # Create alias for root key config.alias_setting(:base_currency, to: :currency) # Create alias for nested key config.alias_setting(:settings, :primary_color, to: [:settings, :color]) config.alias_setting("settings.primary_color", to: [:theme, :color]) # Access via original or alias config.fetch(:base_currency) # => "USD" config.fetch(:currency) # => "USD" config.fetch(:settings, :color) # => "#FF5733" config.fetch(:theme, :color) # => "#FF5733" ``` -------------------------------- ### Parse Command-Line Arguments with optparse Source: https://github.com/piotrmurach/tty-config/blob/master/README.md This snippet shows how to use Ruby's optparse library to define and parse command-line flags such as --host, --port, and --config. It stores the parsed options in a hash, which can then be used to override configuration file settings. ```ruby require "optparse" options = {} option_parser = OptionParser.new do |opts| opts.on("-h", "--host HOSTNAME_OR_IP", "Hostname or IP Adress") do |h| options[:host] = h end opts.on("-p", "--port PORT", "Port of application", Integer) do |p| options[:port] = p end opts.on("-c", "--config FILE", "Read config values from file (defaults: ./config.yml, ~/.config.yml") do |c| options[:config_file_path] = c end ... end option_parser.parse! ``` -------------------------------- ### Fetch Configuration Value (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md The `fetch` method retrieves a configuration setting. It allows specifying a default value using `:default` or a lazy-evaluated block. Nested values can be accessed using multiple keys or a dot-separated string. It supports indifferent access for string and symbol keys. ```ruby config.fetch(:base, default: "USD") config.fetch(:base) { "USD" } config.fetch(:settings, :base) # => USD config.fetch("settings.base") config.fetch(:settings, "base") ``` -------------------------------- ### Prepend Configuration Search Paths in TTY::Config (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Details how to add directories to the beginning of the TTY::Config search path using the `prepend_path` method. This ensures that configuration files in these paths are checked first. ```ruby config.append_path(Dir.pwd) config.prepend_path(Dir.home) ``` -------------------------------- ### Merging Configuration Source: https://context7.com/piotrmurach/tty-config/llms.txt Explains how to merge external hash data into the current configuration using the `merge` method for deep merging. ```APIDOC ## POST /config/merge ### Description Merges external hash settings into the current configuration, performing a deep merge for nested structures. ### Method `merge(hash)` ### Endpoint N/A (This is a method call, not an HTTP endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **hash** (Hash) - The hash containing settings to merge into the configuration. ### Request Example ```ruby config = TTY::Config.new config.set(:database, :host, value: "localhost") config.set(:database, :port, value: 5432) external_settings = { database: { host: "192.168.1.1", username: "admin" }, logging: { level: "debug" } } config.merge(external_settings) config.fetch(:database, :host) # => "192.168.1.1" (overwritten) config.fetch(:database, :port) # => 5432 (original value preserved) config.fetch(:database, :username) # => "admin" (newly added) config.fetch(:logging, :level) # => "debug" (newly added) ``` ### Response #### Success Response (200) Returns the configuration object for chaining. #### Response Example (No specific response body, returns the config object) ``` -------------------------------- ### Write Configuration File with TTY::Config Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Persists configuration to a file. Allows specifying filename, extension, and custom locations. Supports creating missing directories and overwriting existing files with options like `:create` and `:force`. ```ruby config.filename = "investments" config.extname = ".toml" config.write ``` ```ruby config.write("/custom/path/to/investments.toml") ``` ```ruby config.write(path: "/custom/path/to") ``` ```ruby config.write("/custom/path/to/investments.toml", create: true) config.write(path: "/custom/path/to", create: true) ``` ```ruby config.write(force: true) config.write("/custom/path/to/investments.toml", force: true) config.write(path: "/custom/path/to", force: true) ``` ```ruby config.append_path("/custom/path/to") ``` ```ruby config.write(create: true, force: true) ``` -------------------------------- ### Environment Variable Prefix Source: https://context7.com/piotrmurach/tty-config/llms.txt Sets a prefix for environment variable names, making it easier to namespace your application's env vars. ```APIDOC ## env_prefix= ### Description Sets a prefix for environment variable names, making it easier to namespace your application's env vars. ### Method Set Environment Variable Prefix ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby ENV["MYAPP_HOST"] = "127.0.0.1" ENV["MYAPP_PORT"] = "3000" ENV["MYAPP_DEBUG"] = "true" config = TTY::Config.new config.env_prefix = "myapp" # Bind keys to prefixed env vars config.set_from_env(:host) # Looks for MYAPP_HOST config.set_from_env(:port) # Looks for MYAPP_PORT config.set_from_env(:debug) # Looks for MYAPP_DEBUG config.fetch(:host) # => "127.0.0.1" config.fetch(:port) # => "3000" config.fetch(:debug) # => "true" ``` ### Response #### Success Response (200) Sets the environment variable prefix for the configuration object. #### Response Example ```ruby # No direct return value, configuration is updated. ``` ``` -------------------------------- ### Auto-loading Environment Variables Source: https://context7.com/piotrmurach/tty-config/llms.txt Automatically loads all environment variables matching the prefix without explicit binding. ```APIDOC ## autoload_env ### Description Automatically loads all environment variables matching the prefix without explicit binding. ### Method Auto-load Environment Variables ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby ENV["MYAPP_HOST"] = "localhost" ENV["MYAPP_PORT"] = "8080" ENV["MYAPP_DATABASE_URL"] = "postgres://localhost/db" ENV["OTHER_VAR"] = "ignored" config = TTY::Config.new config.env_prefix = "myapp" config.autoload_env # Any MYAPP_* env var is automatically available config.fetch(:host) # => "localhost" config.fetch(:port) # => "8080" config.fetch(:database_url) # => "postgres://localhost/db" # Non-prefixed vars are not loaded config.fetch(:other_var) # => nil ``` ### Response #### Success Response (200) Loads all environment variables matching the configured prefix into the configuration object. #### Response Example ```ruby # No direct return value, configuration is updated. ``` ``` -------------------------------- ### Path Configuration Source: https://context7.com/piotrmurach/tty-config/llms.txt Configure search paths for reading configuration files. Paths are searched in order when reading. ```APIDOC ## append_path and prepend_path ### Description Configure search paths for reading configuration files. Paths are searched in order when reading. ### Method Append/Prepend Path ### Endpoint N/A (Instance Methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby config = TTY::Config.new config.filename = "myapp" # Add paths to search (append adds to end, prepend adds to beginning) config.append_path("/etc/myapp") # Search third config.append_path(Dir.home) # Search fourth config.prepend_path(Dir.pwd) # Search first (inserted at beginning) config.prepend_path("./config") # Search first (inserted at beginning again) # Final search order: ./config, current_dir, /etc/myapp, home_dir config.location_paths # => ["./config", "/current/working/dir", "/etc/myapp", "/home/user"] ``` ### Response #### Success Response (200) Returns an array of strings representing the configured search paths. #### Response Example ```ruby # => ["./config", "/current/working/dir", "/etc/myapp", "/home/user"] ``` ``` -------------------------------- ### Write Configuration Files with write Source: https://context7.com/piotrmurach/tty-config/llms.txt Writes the current configuration to a file. Options include overwriting existing files and creating necessary directories. It can write to the default location or a custom path. ```ruby config = TTY::Config.new config.filename = "investments" config.extname = ".yml" config.append_path(Dir.pwd) config.set(:settings, :base, value: "USD") config.set(:settings, :color, value: true) config.set(:coins, value: ["BTC", "ETH", "TRX"]) # Write to default location (current directory) config.write # Write with force overwrite config.write(force: true) # Write to custom path, creating directories if needed config.write("/custom/path/to/investments.toml", create: true, force: true) # Write to custom directory with current filename config.write(path: "/etc/myapp", create: true, force: true) # Output file (investments.yml): # --- # settings: # base: USD # color: true # coins: # - BTC # - ETH # - TRX ``` -------------------------------- ### Initialize TTY::Config and set filename Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Initializes a new TTY::Config object and sets the base filename for configuration files. This is the first step in managing application settings. ```ruby config = TTY::Config.new config.filename = "investments" ``` -------------------------------- ### Check Configuration File Existence with exist? Source: https://context7.com/piotrmurach/tty-config/llms.txt Checks if a configuration file exists within the configured search paths. This method is useful for conditionally loading configurations or providing default settings. ```ruby config = TTY::Config.new config.filename = "investments" config.append_path(Dir.pwd) config.append_path(Dir.home) if config.exist? config.read puts "Configuration loaded from: #{config.source_file}" else puts "No configuration file found, using defaults" config.set(:settings, :base, value: "USD") end ``` -------------------------------- ### Set Configuration File Extension in TTY::Config (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Demonstrates how to change the default file extension used for writing configuration files from `.yml` to another supported extension like `.toml` using the `extname=` method. ```ruby config.extname = ".toml" ``` -------------------------------- ### Read configuration from a file Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Loads configuration settings from a specified file. Before reading, paths to search for the configuration file should be added using `append_path`. ```ruby config.append_path Dir.pwd config.append_path Dir.home config.read ``` -------------------------------- ### Check Configuration File Existence with TTY::Config Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Checks if a configuration file exists within the configured search paths using the `exist?` method. Returns `true` if found, `false` otherwise. ```ruby config.exist? ``` -------------------------------- ### Reading Configuration Source: https://context7.com/piotrmurach/tty-config/llms.txt Reads configuration from a file. Automatically detects format from extension or allows explicit format specification. ```APIDOC ## read ### Description Reads configuration from a file. Automatically detects format from extension or allows explicit format specification. ### Method Read Configuration ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby config = TTY::Config.new config.filename = "investments" config.append_path(Dir.pwd) # Read from configured paths (searches for investments.yml, investments.json, etc.) config.read # Read from specific file path config.read("./config/investments.toml") # Read with explicit format (for non-standard extensions) config.read("./settings.conf", format: :yaml) # Example: investments.yml content # --- # settings: # base: USD # color: true # coins: # - BTC # - ETH config.fetch(:settings, :base) # => "USD" config.fetch(:coins) # => ["BTC", "ETH"] # Handle missing file begin config.read("./nonexistent.yml") rescue TTY::Config::ReadError => e puts "Config not found: #{e.message}" end ``` ### Response #### Success Response (200) Returns the configuration data loaded from the file. #### Response Example ```ruby # For investments.yml: # config.fetch(:settings, :base) # => "USD" # config.fetch(:coins) # => ["BTC", "ETH"] ``` ``` -------------------------------- ### Merge Configuration Settings (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md The `merge` method integrates another hash into the current configuration. Existing values may be overwritten. This is useful for combining configurations from different sources. ```ruby config.set(:a, :b, value: 1) config.set(:a, :c, value: 2) config.merge({"a" => {"c" => 3, "d" => 4}}) config.fetch(:a, :c) # => 3 config.fetch(:a, :d) # => 4 ``` -------------------------------- ### Merge External Settings into Configuration Source: https://context7.com/piotrmurach/tty-config/llms.txt Demonstrates the `merge` method for incorporating external hash data into the existing configuration, performing a deep merge for nested structures. ```ruby config = TTY::Config.new config.set(:database, :host, value: "localhost") config.set(:database, :port, value: 5432) external_settings = { database: { host: "192.168.1.1", username: "admin" }, logging: { level: "debug" } } config.merge(external_settings) config.fetch(:database, :host) # => "192.168.1.1" (overwritten) config.fetch(:database, :port) # => 5432 (original preserved) config.fetch(:database, :username) # => "admin" (newly added) config.fetch(:logging, :level) # => "debug" (newly added) ``` -------------------------------- ### Check Existence Source: https://context7.com/piotrmurach/tty-config/llms.txt Checks if a configuration file exists in the configured search paths. ```APIDOC ## exist? ### Description Checks if a configuration file exists in the configured search paths. ### Method Check Existence ### Endpoint N/A (Instance Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby config = TTY::Config.new config.filename = "investments" config.append_path(Dir.pwd) config.append_path(Dir.home) if config.exist? config.read puts "Configuration loaded from: #{config.source_file}" else puts "No configuration file found, using defaults" config.set(:settings, :base, value: "USD") end ``` ### Response #### Success Response (200) Returns `true` if a configuration file is found, `false` otherwise. #### Response Example ```ruby # => true (if file exists) # => false (if file does not exist) ``` ``` -------------------------------- ### Validate Configuration Values in TTY::Config (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Illustrates how to use the `validate` method to enforce data consistency for configuration values. It allows defining validation rules using blocks that are executed when values are set or fetched. ```ruby config.validate(:settings, :base) do |key, value| if value.length != 3 raise TTY::Config::ValidationError, "Currency code needs to be 3 chars long." end end config.set(:settings, :base, value: "PL") # raises TTY::Config::ValidationError, "Currency code needs to be 3 chars long." config.set(:settings, :base) { "PL" } config.fetch(:settings, :base) # raises TTY::Config::ValidationError, "Currency code needs to be 3 chars long." ``` -------------------------------- ### Read Configuration File with TTY::Config Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Reads configuration files using the `read` method. It supports multiple formats and allows for automatic extension guessing or explicit format specification. Search paths and filenames can be configured. ```ruby config.append_path(Dir.pwd) config.filename = "investments" config.read ``` ```ruby config.read("./investments.toml") ``` ```ruby config.read("investments.config", format: :yaml) ``` -------------------------------- ### Coerce Hash to Configuration (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md The `TTY::Config.coerce` class method initializes a configuration object from a hash, automatically converting all keys to symbols. This provides a convenient way to load initial configuration data. ```ruby hash = {"settings" => {"base" => "USD", "exchange" => "CCCAGG"}} config = TTY::Config.coerce(hash) config.to_h # => # {settings: {base: "USD", exchange: "CCCAGG"}} ``` -------------------------------- ### Conditionally Set Values with `set_if_empty` Source: https://context7.com/piotrmurach/tty-config/llms.txt Illustrates the use of `set_if_empty` to set a configuration value only if the key does not already exist, useful for applying default settings. ```ruby config = TTY::Config.new # Set initial value config.set(:theme, value: "dark") # Attempt to set again - will NOT overwrite config.set_if_empty(:theme, value: "light") # Set a new key - will set since it's empty config.set_if_empty(:language, value: "en") config.fetch(:theme) # => "dark" (original value preserved) config.fetch(:language) # => "en" (new value set) ``` -------------------------------- ### Set Configuration from Environment Variables (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md The `set_from_env` method reads configuration options from environment variables. The environment variable name is case-insensitive. It can map environment variables to different configuration keys using a block. Nested settings and custom separators are also supported. ```ruby ENV["HOST"] = "192.168.1.17" ENV["PORT"] = "7727" config.set_from_env(:host) config.set_from_env(:port) config.set_from_env(:host) { "HOSTNAME" } config.set_from_env(:host) { :hostname } config.set_from_env(:settings, :base) { "CURRENCY" } config.set_from_env(:settings, :base) { :currency } config.set_from_env("settings.base") { "CURRENCY" } config.set_from_env("settings.base") { :currency } ``` -------------------------------- ### Configure Search Paths with append_path and prepend_path Source: https://context7.com/piotrmurach/tty-config/llms.txt Configure search paths for reading configuration files using `append_path` and `prepend_path`. Paths are searched in the order they are added, with `prepend_path` adding to the beginning and `append_path` adding to the end. ```ruby config = TTY::Config.new config.filename = "myapp" # Add paths to search (append adds to end, prepend adds to beginning) config.append_path("/etc/myapp") # Search third config.append_path(Dir.home) # Search fourth config.prepend_path(Dir.pwd) # Search first (inserted at beginning) config.prepend_path("./config") # Search first (inserted at beginning again) # Final search order: ./config, current_dir, /etc/myapp, home_dir config.location_paths # => ["./config", "/current/working/dir", "/etc/myapp", "/home/user"] ``` -------------------------------- ### Alias Configuration Settings in TTY::Config (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Explains how to create aliases for existing configuration settings using the `alias_setting` method. This allows accessing a setting through a different name, including deeply nested ones. ```ruby config.set(:base, value: "baz") config.alias_setting(:base, to: :currency) config.fetch(:currency) # => "USD" config.set(:settings, :base, value: "USD") config.alias_setting(:settings, :base, to: [:settings, :currency]) config.alias_setting("settings.base", to [:settings, :currency]) config.fetch(:settings, :currency) # => "USD" config.fetch("settings.currency") # => "USD" ``` -------------------------------- ### Read Configuration Files with read Source: https://context7.com/piotrmurach/tty-config/llms.txt Reads configuration from a file. The format is automatically detected from the file extension or can be explicitly specified. It searches configured paths for the specified filename. ```ruby config = TTY::Config.new config.filename = "investments" config.append_path(Dir.pwd) # Read from configured paths (searches for investments.yml, investments.json, etc.) config.read # Read from specific file path config.read("./config/investments.toml") # Read with explicit format (for non-standard extensions) config.read("./settings.conf", format: :yaml) # Example: investments.yml content # --- # settings: # base: USD # color: true # coins: # - BTC # - ETH config.fetch(:settings, :base) # => "USD" config.fetch(:coins) # => ["BTC", "ETH"] # Handle missing file begin config.read("./nonexistent.yml") rescue TTY::Config::ReadError => e puts "Config not found: #{e.message}" end ``` -------------------------------- ### Append Configuration Search Paths in TTY::Config (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Explains how to add directories to the TTY::Config search path for configuration files using the `append_path` method. This allows specifying multiple locations to look for configuration. ```ruby config.append_path("/etc/") config.append_path(Dir.home) config.append_path(Dir.pwd) ``` -------------------------------- ### Auto-load Environment Variables with TTY::Config (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Explains how to use the `autoload_env` method in TTY::Config to automatically load environment variables. It shows setting an environment prefix and then fetching a configuration value that corresponds to an environment variable. ```ruby ENV["MYTOOL_HOST"] = "localhost" config.env_prefix = "mytool" config.autoload_env config.fetch(:host) # => "localhost" ``` -------------------------------- ### Set Configuration Value if Empty (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md The `set_if_empty` method sets a configuration value only if it has not been previously set. It supports nested keys similar to the `set` method. ```ruby config.set_if_empty(:base, value: "USD") config.set_if_empty(:settings, :base, value: "USD") ``` -------------------------------- ### Set Configuration Value (Ruby) Source: https://github.com/piotrmurach/tty-config/blob/master/README.md The `set` method configures a setting. It accepts keys and a value either directly or via a block. Deeply nested settings can be specified using a sequence of keys or a dot-separated string. Internally, keys are stored as strings. ```ruby config.set(:base, value: "USD") config.set(:base) { "USD" } config.set(:settings, :base, value: "USD") config.set("settings.base", value: "USD") ``` -------------------------------- ### Write configuration to a file Source: https://github.com/piotrmurach/tty-config/blob/master/README.md Persists the current configuration object to a file, typically in YAML format by default. This saves the application's settings. ```ruby config.write # => # --- # settings: # base: USD # color: true # coins: # - BTC # - ETH # - TRX # - DASH ``` -------------------------------- ### Automatically Load Environment Variables with autoload_env Source: https://context7.com/piotrmurach/tty-config/llms.txt Automatically loads all environment variables that match the configured prefix without requiring explicit binding for each variable. This simplifies the process of loading environment-specific settings. ```ruby ENV["MYAPP_HOST"] = "localhost" ENV["MYAPP_PORT"] = "8080" ENV["MYAPP_DATABASE_URL"] = "postgres://localhost/db" ENV["OTHER_VAR"] = "ignored" config = TTY::Config.new config.env_prefix = "myapp" config.autoload_env # Any MYAPP_* env var is automatically available config.fetch(:host) # => "localhost" config.fetch(:port) # => "8080" config.fetch(:database_url) # => "postgres://localhost/db" # Non-prefixed vars are not loaded config.fetch(:other_var) # => nil ``` -------------------------------- ### Merge Additional Settings (Deep Merge) with TTY::Config Source: https://context7.com/piotrmurach/tty-config/llms.txt Demonstrates how to merge additional settings into an existing TTY::Config object using a deep merge strategy. This allows overwriting existing keys and adding new ones within nested structures. ```ruby config = TTY::Config.new config.merge({ "database" => { "port" => 3306, # Overwrite existing "name" => "myapp_prod" # Add new key }, "cache" => { "enabled" => true } }) config.fetch(:database, :host) # => "localhost" (preserved) config.fetch(:database, :port) # => 3306 (overwritten) config.fetch(:database, :name) # => "myapp_prod" (added) config.fetch(:cache, :enabled) # => true (new section) ```