{"id":15512732,"url":"https://github.com/piotrmurach/tty-config","last_synced_at":"2025-06-12T13:09:25.868Z","repository":{"id":56897135,"uuid":"128643078","full_name":"piotrmurach/tty-config","owner":"piotrmurach","description":"A highly customisable application configuration interface for building terminal tools.","archived":false,"fork":false,"pushed_at":"2025-04-27T18:53:39.000Z","size":216,"stargazers_count":67,"open_issues_count":3,"forks_count":8,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-05-28T03:16:56.052Z","etag":null,"topics":["cli","configuration","hcl","ini","ini-config","ruby","rubygem","terminal","toml","toml-config","tty","yaml","yaml-configuration"],"latest_commit_sha":null,"homepage":"http://ttytoolkit.org","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/piotrmurach.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"piotrmurach"}},"created_at":"2018-04-08T13:17:11.000Z","updated_at":"2025-04-29T12:04:16.000Z","dependencies_parsed_at":"2024-01-05T00:16:55.812Z","dependency_job_id":"e3dd13e6-b9d6-4490-9384-7d9719a8f6d6","html_url":"https://github.com/piotrmurach/tty-config","commit_stats":{"total_commits":204,"total_committers":3,"mean_commits":68.0,"dds":0.009803921568627416,"last_synced_commit":"89bdc6ef9bc72f309e2baf6db21522444c496c48"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"purl":"pkg:github/piotrmurach/tty-config","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piotrmurach%2Ftty-config","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piotrmurach%2Ftty-config/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piotrmurach%2Ftty-config/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piotrmurach%2Ftty-config/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/piotrmurach","download_url":"https://codeload.github.com/piotrmurach/tty-config/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/piotrmurach%2Ftty-config/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259470951,"owners_count":22862999,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cli","configuration","hcl","ini","ini-config","ruby","rubygem","terminal","toml","toml-config","tty","yaml","yaml-configuration"],"created_at":"2024-10-02T09:53:49.341Z","updated_at":"2025-06-12T13:09:25.839Z","avatar_url":"https://github.com/piotrmurach.png","language":"Ruby","funding_links":["https://github.com/sponsors/piotrmurach"],"categories":["Ruby"],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"https://ttytoolkit.org\"\u003e\u003cimg width=\"130\" src=\"https://github.com/piotrmurach/tty/raw/master/images/tty.png\" alt=\"TTY Toolkit logo\" /\u003e\u003c/a\u003e\n\u003c/div\u003e\n\n# TTY::Config\n\n[![Gem Version](https://badge.fury.io/rb/tty-config.svg)][gem]\n[![Actions CI](https://github.com/piotrmurach/tty-config/actions/workflows/ci.yml/badge.svg)][gh_actions_ci]\n[![Build status](https://ci.appveyor.com/api/projects/status/2383i0dn3hlw9cnn?svg=true)][appveyor]\n[![Maintainability](https://api.codeclimate.com/v1/badges/dfac05073e1549e9dbb6/maintainability)][codeclimate]\n[![Coverage Status](https://coveralls.io/repos/github/piotrmurach/tty-config/badge.svg)][coverage]\n\n[gem]: https://badge.fury.io/rb/tty-config\n[gh_actions_ci]: https://github.com/piotrmurach/tty-config/actions/workflows/ci.yml\n[appveyor]: https://ci.appveyor.com/project/piotrmurach/tty-config\n[codeclimate]: https://codeclimate.com/github/piotrmurach/tty-config/maintainability\n[coverage]: https://coveralls.io/github/piotrmurach/tty-config\n\n\u003e A highly customisable application configuration interface for building terminal tools.\n\n**TTY::Config** provides application configuration component for [TTY](https://github.com/piotrmurach/tty) toolkit.\n\n## Features\n\nThis is a one-stop shop for all your configuration needs:\n\n* [Read](#216-read) and [write](#217-write) config files in YAML, JSON, TOML, INI, XML, HCL and Java Properties formats\n* Add [custom marshallers](#222-register_marshaller) or override the built-in ones\n* [Set](#21-set) and [read](#24-fetch) settings for deeply nested keys\n* [Set](#21-set) defaults for undefined settings\n* [Read](#24-fetch) settings with indifferent access\n* [Merge](#25-merge) configuration settings from other hash objects\n* Read values from [environment variables](#23-set_from_env)\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem \"tty-config\"\n```\n\nAnd then execute:\n\n    $ bundle\n\nOr install it yourself as:\n\n    $ gem install tty-config\n\n## Contents\n\n* [1. Usage](#1-usage)\n  * [1.1 app](#11-app)\n* [2. Interface](#2-interface)\n  * [2.1 set](#21-set)\n  * [2.2 set_if_empty](#22-set_if_empty)\n  * [2.3 set_from_env](#23-set_from_env)\n  * [2.4 fetch](#24-fetch)\n  * [2.5 merge](#25-merge)\n  * [2.6 coerce](#26-coerce)\n  * [2.7 append](#27-append)\n  * [2.8 remove](#28-remove)\n  * [2.9 delete](#29-delete)\n  * [2.10 alias_setting](#210-alias_setting)\n  * [2.11 validate](#211-validate)\n  * [2.12 filename=](#212-filename)\n  * [2.13 extname=](#213-extname)\n  * [2.14 append_path](#214-append_path)\n  * [2.15 prepend_path](#215-prepend_path)\n  * [2.16 read](#216-read)\n  * [2.17 write](#217-write)\n  * [2.18 exist?](#218-exist)\n  * [2.19 env_prefix=](#219-env_prefix)\n  * [2.20 env_separator=](#220-env_separator)\n  * [2.21 autoload_env](#221-autoload_env)\n  * [2.22 register_marshaller](#222-register_marshaller)\n  * [2.23 unregister_marshaller](#223-unregister_marshaller)\n* [3. Examples](#3-examples)\n  * [3.1 Working with env vars](#31-working-with-env-vars)\n  * [3.2 Working with optparse](#32-working-with-optparse)\n\n## 1. Usage\n\nInitialize the configuration and provide the name:\n\n```ruby\nconfig = TTY::Config.new\nconfig.filename = \"investments\"\n```\n\nThen configure values for different nested keys with `set` and `append`:\n\n```ruby\nconfig.set(:settings, :base, value: \"USD\")\nconfig.set(:settings, :color, value: true)\nconfig.set(:coins, value: [\"BTC\"])\n\nconfig.append(\"ETH\", \"TRX\", \"DASH\", to: :coins)\n```\n\nYou can get any value by using `fetch`:\n\n```ruby\nconfig.fetch(:settings, :base)\n# =\u003e \"USD\"\n\nconfig.fetch(:coins)\n# =\u003e [\"BTC\", \"ETH\", \"TRX\", \"DASH\"]\n```\n\nAnd call `write` to persist the configuration to `investments.yml` file:\n\n```ruby\nconfig.write\n# =\u003e\n# ---\n# settings:\n#   base: USD\n#   color: true\n# coins:\n#  - BTC\n#  - ETH\n#  - TRX\n#  - DASH\n```\n\nTo read an `investments.yml` file, you need to provide the locations to search in:\n\n```ruby\nconfig.append_path Dir.pwd\nconfig.append_path Dir.home\n```\n\nFinally, call `read` to convert configuration file back into an object again:\n\n```ruby\nconfig.read\n```\n\n### 1.1 app\n\nAn example of an application configuration:\n\n```ruby\nclass App\n  attr_reader :config\n\n  def initialize\n    @config = TTY::Config.new\n    @config.filename = \"investments\"\n    @config.extname = \".toml\"\n    @config.append_path Dir.pwd\n    @config.append_path Dir.home\n  end\n\n  def self.config\n    @config ||= self.class.new.config\n  end\nend\n```\n\n## 2. Interface\n\n### 2.1 set\n\nTo set configuration setting use `set` method. It accepts any number of keys and value by either using `:value` keyword argument or passing a block:\n\n```ruby\nconfig.set(:base, value: \"USD\")\nconfig.set(:base) { \"USD\" }\n```\n\nThe block version of specifying a value will mean that the value is evaluated every time it's being read.\n\nYou can also specify deeply nested configuration settings by passing sequence of keys:\n\n```ruby\nconfig.set(:settings, :base, value: \"USD\")\n```\n\nWhich is equivalent to:\n\n```ruby\nconfig.set(\"settings.base\", value: \"USD\")\n```\n\nInternally all configuration settings are stored as string keys for ease of working with configuration files and command line application's inputs.\n\n### 2.2 set_if_empty\n\nTo set a configuration setting only if it hasn't been set before use `set_if_empty`:\n\n```ruby\nconfig.set_if_empty(:base, value: \"USD\")\n```\n\nSimilar to `set` it allows you to specify arbitrary sequence of keys followed by a key value or block:\n\n```ruby\nconfig.set_if_empty(:settings, :base, value: \"USD\")\n```\n\n### 2.3 set_from_env\n\nTo read configuration options from environment variables use `set_from_env`. At minimum it requires a single argument which will match the name of `ENV` variable. The name of this parameter is case insensitive.\n\nGiven the following environment variables:\n\n```ruby\nENV[\"HOST\"] = \"192.168.1.17\"\nENV[\"PORT\"] = \"7727\"\n```\n\nYou can make the config aware of the above env variables:\n\n```ruby\nconfig.set_from_env(:host)\nconfig.set_from_env(:port)\n```\n\nThen you can retrieve values like any other configuration option:\n\n```ruby\nconfig.fetch(:host)\n# =\u003e \"192.168.1.17\"\nconfig.fetch(:port)\n# =\u003e \"7727\"\n```\n\nIf you want the configuration key name to be different from `ENV` variable name use a block:\n\n```ruby\nconfig.set_from_env(:host) { \"HOSTNAME\" }\nconfig.set_from_env(:host) { :hostname }\n```\n\nYou can also configure settings for deeply nested keys:\n\n```ruby\nconfig.set_from_env(:settings, :base) { \"CURRENCY\" }\nconfig.set_from_env(:settings, :base) { :currency }\nconfig.set_from_env(\"settings.base\") { \"CURRENCY\" }\nconfig.set_from_env(\"settings.base\") { :currency }\n```\n\nAnd assuming `ENV[\"CURRENCY\"]=USD`:\n\n```ruby\nconfig.fetch(:settings, :base)\n# =\u003e USD\n```\n\nYou can also prefix your environment variables with [env_prefix=](#219-env_prefix) or use a different separator with [env_separator](#220-env_separator).\n\nIt's important to recognise that `set_from_env` doesn't record the value for the environment variables. They are read each time from the `ENV` when `fetch` is called.\n\n### 2.4 fetch\n\nTo get a configuration setting use `fetch`, which can accept default value either with a `:default` keyword or a block that will be lazy evaluated:\n\n```ruby\nconfig.fetch(:base, default: \"USD\")\nconfig.fetch(:base) { \"USD\" }\n```\n\nSimilar to `set` operation, `fetch` allows you to retrieve deeply nested values:\n\n```ruby\nconfig.fetch(:settings, :base) # =\u003e USD\n```\n\nWhich is equivalent to:\n\n```ruby\nconfig.fetch(\"settings.base\")\n```\n\n`fetch` has indifferent access so you can mix string and symbol keys, all the following examples retrieve the value:\n\n```ruby\nconfig.fetch(:settings, :base)\nconfig.fetch(\"settings\", \"base\")\nconfig.fetch(:settings, \"base\")\nconfig.fetch(\"settings\", :base)\n```\n\n### 2.5 merge\n\nTo merge in other configuration settings as hash use `merge`:\n\n```ruby\nconfig.set(:a, :b, value: 1)\nconfig.set(:a, :c, value: 2)\n\nconfig.merge({\"a\" =\u003e {\"c\" =\u003e 3, \"d\" =\u003e 4}})\n\nconfig.fetch(:a, :c) # =\u003e 3\nconfig.fetch(:a, :d) # =\u003e 4\n```\n\nInternally all configuration settings are stored as string keys for ease of working with file values and command line applications inputs.\n\n### 2.6 coerce\n\nYou can initialize configuration based on a hash, with all the keys converted to symbols:\n\n```ruby\nhash = {\"settings\" =\u003e {\"base\" =\u003e \"USD\", \"exchange\" =\u003e \"CCCAGG\"}}\nconfig = TTY::Config.coerce(hash)\nconfig.to_h\n# =\u003e\n# {settings: {base: \"USD\", exchange: \"CCCAGG\"}}\n```\n\n### 2.7 append\n\nTo append arbitrary number of values to a value under a given key use `append`:\n\n```ruby\nconfig.set(:coins) { [\"BTC\"] }\n\nconfig.append(\"ETH\", \"TRX\", to: :coins)\n# =\u003e\n# {coins: [\"BTC\", \"ETH\", \"TRX\"]}\n```\n\nYou can also append values to deeply nested keys:\n\n```ruby\nconfig.set(:settings, :bases, value: [\"USD\"])\n\nconfig.append(\"EUR\", \"GBP\", to: [:settings, :bases])\n# =\u003e\n# {settings: {bases: [\"USD\", \"EUR\", \"GBP\"]}}\n```\n\n### 2.8 remove\n\nUse `remove` to remove a set of values from a key.\n\n```ruby\nconfig.set(:coins, value: [\"BTC\", \"TRX\", \"ETH\", \"DASH\"])\n\nconfig.remove(\"TRX\", \"DASH\", from: :coins)\n# =\u003e\n# [\"BTC\", \"ETH\"]\n```\n\nIf the key is nested the `:from` accepts an array:\n\n```ruby\nconfig.set(:holdings, :coins, value: [\"BTC\", \"TRX\", \"ETH\", \"DASH\"])\n\nconfig.remove(\"TRX\", \"DASH\", from: [:holdings, :coins])\n# =\u003e\n# [\"BTC\", \"ETH\"]\n```\n\n### 2.9 delete\n\nTo completely delete a value and corresponding key use `delete`:\n\n```ruby\nconfig.set(:base, value: \"USD\")\nconfig.delete(:base)\n# =\u003e\n# \"USD\"\n```\n\nYou can also delete deeply nested keys and their values:\n\n```ruby\nconfig.set(:settings, :base, value: \"USD\")\nconfig.delete(:settings, :base)\n# =\u003e\n# \"USD\"\n```\n\nYou can provide an optional default value in a block that will be returned when a key is not set:\n\n```ruby\nconfig.delete(:settings, :unknown) { |key| \"#{key} isn't set\" }\n# =\u003e\n# \"unknown isn't set\"\n```\n\n### 2.10 alias_setting\n\nIn order to alias a configuration setting to another name use `alias_setting`.\n\nFor example, given an already existing setting:\n\n```ruby\nconfig.set(:base, value: \"baz\")\n```\n\nYou can alias it to another name:\n\n```ruby\nconfig.alias_setting(:base, to: :currency)\n```\n\nAnd then access like any other configuration setting:\n\n```ruby\nconfig.fetch(:currency)\n# =\u003e \"USD\"\n```\n\nDeep nested configuration options are also supported:\n\n```ruby\nconfig.set(:settings, :base, value: \"USD\")\n```\n\nAnd then can be aliased like so:\n\n```ruby\nconfig.alias_setting(:settings, :base, to: [:settings, :currency])\nconfig.alias_setting(\"settings.base\", to [:settings, :currency])\n```\n\nYou can then access the deep nested settings:\n\n```ruby\nconfig.fetch(:settings, :currency)\n# =\u003e \"USD\"\nconfig.fetch(\"settings.currency\")\n# =\u003e \"USD\"\n```\n\n### 2.11 validate\n\nTo ensure consistency of the data, you can validate values being set at arbitrarily deep keys using `validate` method, that takes an arbitrarily nested key as its argument and a validation block.\n\n```ruby\nconfig.validate(:settings, :base) do |key, value|\n  if value.length != 3\n    raise TTY::Config::ValidationError, \"Currency code needs to be 3 chars long.\"\n  end\nend\n```\n\nYou can assign multiple validations for a given key and each of them will be run in the order they were registered when checking a value.\n\nWhen setting value all the validations will be run:\n\n```ruby\nconfig.set(:settings, :base, value: \"PL\")\n# raises TTY::Config::ValidationError, \"Currency code needs to be 3 chars long.\"\n```\n\nIf the value is provided as a proc or a block then the validation will be delayed until the value is actually read:\n\n```ruby\nconfig.set(:settings, :base) { \"PL\" }\nconfig.fetch(:settings, :base)\n# raises TTY::Config::ValidationError, \"Currency code needs to be 3 chars long.\"\n```\n\n### 2.12 filename=\n\nBy default, **TTY::Config** searches for `config` named configuration file. To change this use `filename=` method without the extension name:\n\n```ruby\nconfig.filename = \"investments\"\n```\n\nThen any supported extensions will be searched for such as `.yml`, `.json` and `.toml`.\n\n### 2.13 extname=\n\nBy default \".yml\" extension is used to write configuration out to a file but you can change that with `extname=`:\n\n```ruby\nconfig.extname = \".toml\"\n```\n\n### 2.14 append_path\n\nYou need to tell the **TTY::Config** where to search for configuration files. To search multiple paths for a configuration file use `append_path` or `prepend_path` methods.\n\nFor example, if you want to search through `/etc` directory first, then user home directory and then current directory do:\n\n```ruby\nconfig.append_path(\"/etc/\")   # look in /etc directory\nconfig.append_path(Dir.home)  # look in user's home directory\nconfig.append_path(Dir.pwd)   # look in current working directory\n```\n\nNone of these paths are required, but you should provide at least one path if you wish to read a configuration file.\n\n### 2.15 prepend_path\n\nThe `prepend_path` allows you to add configuration search paths that should be searched first.\n\n```ruby\nconfig.append_path(Dir.pwd)   # look in current working directory second\nconfig.prepend_path(Dir.home) # look in user's home directory first\n```\n\n### 2.16 read\n\nThere are two ways for reading configuration files and both use the `read` method. One attempts to guess extension and format of your data, the other allows you to request specific extension and format.\n\nCurrently the supported file formats are:\n\n* `yaml` for `.yaml`, `.yml` extensions\n* `json` for `.json` extension\n* `toml` for `.toml` extension\n* `ini`  for `.ini`, `.cnf`, `.conf`, `.cfg`, `.cf extensions`\n* `hcl`  for `.hcl` extensions\n* `xml`  for `.xml` extension\n* `jprops` for `.properties`, `.props`, `.prop` extensions\n\nCalling `read` without any arguments searches through provided locations to find configuration file and reads it. Therefore, you need to specify at least one search path that contains the configuration file together with actual filename. When filename is specified then all known extensions will be tried.\n\nFor example, to find file called investments in the current directory do:\n\n```ruby\nconfig.append_path(Dir.pwd)       # look in current working directory\nconfig.filename = \"investments\"   # file to search for\n```\n\nFind and read the configuration file:\n\n```ruby\nconfig.read\n```\n\nYou can also specify directly the file to read without setting up any search paths or filenames. If you specify a configuration with a known file extension, an appropriate format will be guessed, in this instance `TOML`:\n\n```ruby\nconfig.read(\"./investments.toml\")\n```\n\nIn cases where you wish to specify a custom file extension, you will need to also specify the file format to use.\n\nFor example, if you have a configuration file formatted using `YAML` notation with extension called `.config`, to read it do:\n\n```ruby\nconfig.read(\"investments.config\", format: :yaml)\n```\n\n### 2.17 write\n\nBy default **TTY::Config**, persists configuration file in the current working directory with a `config.yml` name. However, you can change the default file name by specifying the `filename` and `extension` type:\n\n```ruby\nconfig.filename = \"investments\"\nconfig.extname = \".toml\"\n```\n\nNow, by invoking `write` you will persist the current configuration to `investments.toml` file.\n\n```ruby\nconfig.write   # writes \"investments.toml\" in the current directory\n```\n\nTo write the current configuration to a file in a custom location, you can specify a direct location path and filename as an argument:\n\n```ruby\nconfig.write(\"/custom/path/to/investments.toml\")\n# may raise an error if any of the path directories are missing\n```\n\nAlternatively, if the filename doesn't need to change you can specify only a custom path using the `:path` keyword:\n\n```ruby\nconfig.write(path: \"/custom/path/to\")\n# may raise an error if any of the path directories are missing\n```\n\nIf the `/custom/path/to` doesn't exist an error will be raised. You can set the `:create` option to make any missing directories in the path:\n\n```ruby\nconfig.write(\"/custom/path/to/investments.toml\", create: true)\nconfig.write(path: \"/custom/path/to\", create: true)\n```\n\nWhen the `investments.toml` file already exists the `TTY::Config::WriteError` error will be raised.\n\nTo create a configuration file regardless of whether it exists or not, use `:force` flag:\n\n```ruby\nconfig.write(force: true)\nconfig.write(\"/custom/path/to/investments.toml\", force: true)\nconfig.write(path: \"/custom/path/to\", force: true)\n```\n\nBy default, only the current directory is searched. You can specify additional location paths to be searched for already existing configuration to overwrite:\n\n```ruby\nconfig.append_path(\"/custom/path/to\")  # search in \"/custom/path/to\" for config file\n```\n\nBy setting the `:create` option to `true`, you can ensure that even when no path is found that has a configuration file, the first location will be used and all missing directories created.\n\nTo ensure that a configuration file is written no matter what, use both `:create` and `:force`:\n\n```ruby\nconfig.write(create: true, force: true)\n```\n\n### 2.18 exist?\n\nTo check if a configuration file exists within the configured search paths use `exist?` method:\n\n```ruby\nconfig.exist? # =\u003e true\n```\n\n### 2.19 env_prefix=\n\nGiven the following variables:\n\n```ruby\nENV[\"MYTOOL_HOST\"] = \"127.0.0.1\"\nENV[\"MYTOOL_PORT\"] = \"7727\"\n```\n\nYou can inform configuration about common prefix using `env_prefix`:\n\n```ruby\nconfig.env_prefix = \"mytool\"\n```\n\nThen set configuration key name to environment variable name:\n\n```ruby\nconfig.set_from_env(:host)\nconfig.set_from_env(:port)\n```\n\nAnd retrieve the value:\n\n```ruby\nconfig.fetch(:host)\n# =\u003e \"127.0.0.1\"\nconfig.fetch(:port)\n# =\u003e \"7727\"\n```\n\n### 2.20 env_separator=\n\nBy default, the `_` character is used to separate parts in the environment variable name and it can be changed using the `env_separator=` like so:\n\n```ruby\nconfig.env_separator = \"___\"\n```\n\nGiven the following environment variable:\n\n```ruby\nENV[\"SERVER__PORT\"] = \"123\"\n```\n\nThen we can make configuration aware of the above variable name in one of these ways:\n\n```ruby\nconfig.set_from_env(:server, :port)\nconfig.set_from_env(\"server.port\")\n````\n\nAnd retrieve the value:\n\n```ruby\nconfig.fetch(:server, :port)\n# =\u003e \"123\"\n```\n\n### 2.21 autoload_env\n\nThe `autoload_env` method allows you to automatically read environment variables. In most cases you would combine it with [env_prefix=](#219-env_prefix) to only read a subset of variables. When using `autoload_env`, anytime the `fetch` is called a corresponding environment variable will be checked.\n\nFor example, given an environment variable `MYTOOL_HOST` set to `localhost`:\n\n```ruby\nENV[\"MYTOOL_HOST\"]=localhost\n```\n\nAnd loading environment variables with a prefix of `MYTOOL`:\n\n```ruby\nconfig.env_prefix = \"mytool\"\nconfig.autoload_env\n```\n\nYou can retrieve value with:\n\n```ruby\nconfig.fetch(:host)\n# =\u003e \"localhost\"\n```\n\n### 2.22 register_marshaller\n\nThere are number of built-in marshallers that handle the process of serializing internal configuration from and back into a desired format, for example, a `JSON` string.\n\nCurrently supported formats out-of-the-box are: `YAML`, `JSON`, `TOML`, `INI`, `XML`, `HCL` \u0026 `Java Properties`.\n\nTo create your own marshaller use the `TTY::Config::Marshaller` interface. You need to provide the implementation for the following marshalling methods:\n\n* `marshal`\n* `unmarshal`\n\nIn addition, you will need to specify the extension types this marshaller will handle using the `extension` method. The method accepts a list of names preceded by a dot:\n\n```ruby\nextension \".ext1\", \".ext2\", \".ext3\"\n```\n\nOptionally, you can provide a dependency or dependencies that will be lazy loaded if the extension is used. For this use the `dependency` method.\n\nYou can either specify dependencies as a list of names:\n\n```ruby\ndependency \"toml\"\ndependency \"toml\", \"tomlrb\"\n```\n\nOr provide dependencies in a block:\n\n```ruby\ndependency do\n  require \"toml\"\n  require \"tomlrb\"\nend\n```\n\nPutting it all together, you can create your own marshaller like so:\n\n```ruby\nclass MyCustomMarshaller\n  include TTY::Config::Marshaller\n\n  dependency \"my_dep\"\n\n  extension \".ext1\", \".ext2\"\n\n  def marshal(object)\n    MyDep.dump(object)\n  end\n\n  def unmarshal(content)\n    MyDep.parse(content)\n  end\nend\n```\n\nAnd then let the configuration know about your marshaller by calling the `register_marshaller`:\n\n```ruby\nconfig.register_marshaller(:my_custom, MyCustomMarshaller)\n```\n\nBear in mind that you can also override the built-in implementation of a marshaller. For example, if you find a better performing Ruby gem for TOML parsing, register your custom marshaller under the `:toml` name like so:\n\n```ruby\nconfig.register_marshaller(:toml, MyTOMLMarshaller)\n```\n\n### 2.23 unregister_marshaller\n\nBy default, the **TTY::Config** is ready to recognize various extensions. See [2.16 read](#216-read) section for more details. But, you're free to remove the default marshallers from the internal registry with `unregister_marshaller` method.\n\nFor example, to remove all the built-in marshallers do:\n\n```ruby\nconfig.unregister_marshaller :yaml, :json, :toml, :ini, :xml, :hcl, :jprops\n```\n\n## 3. Examples\n\n### 3.1 Working with env vars\n\n*TTY::Config* fully supports working with environment variables. For example, there are couple of environment variables that your configuration is interested in, which normally would be set in terminal but for the sake of this example we assign them:\n\n```ruby\nENV[\"MYTOOL_HOST\"] = \"192.168.1.17\"\nENV[\"MYTOOL_PORT\"] = \"7727\"\n```\n\nThen in order to make your configuration aware of the above, you would use [env_prefix=](#219-env_prefix) and [set_from_env](#23-set_from_env):\n\n```ruby\nconfig.env_prefix = \"mytool\"\nconfig.set_from_env(:host)\nconfig.set_from_env(:port)\n```\n\nOr automatically load all prefixed environment variables with [autoload_env](#221-autoload_env):\n\n```ruby\nconfig.env_prefix = \"mytool\"\nconfig.autoload_env\n```\n\nAnd then retrieve values with [fetch](#24-fetch):\n\n```ruby\nconfig.fetch(:host)\n#=\u003e \"192.168.1.17\"\nconfig.fetch(:port)\n# =\u003e \"7727\"\n```\n\n### 3.2 Working with optparse\n\nThis is an example of combining `tty-config` with `optparse` stdlib.\n\nLet's assume you want to create a command line tool that among many options accepts `--host|-h` and `--port|-p` flags. In addition, these flags will take precedence over the options specified in the configuration file.\n\nFirst, you need to parse the flags and store results away in options hash:\n\n```ruby\nrequire \"optparse\"\n\noptions = {}\n\noption_parser = OptionParser.new do |opts|\n  opts.on(\"-h\", \"--host HOSTNAME_OR_IP\", \"Hostname or IP Adress\") do |h|\n    options[:host] = h\n  end\n  opts.on(\"-p\", \"--port PORT\", \"Port of application\", Integer) do |p|\n    options[:port] = p\n  end\n  opts.on(\"-c\", \"--config FILE\",\n         \"Read config values from file (defaults: ./config.yml, ~/.config.yml\") do |c|\n    options[:config_file_path] = c\n  end\n  ...\nend\n\noption_parser.parse!\n```\n\nThen, you create a configuration instance:\n\n```ruby\nconfig = TTY::Config.new\n```\n\nAnd setup config filename:\n\n```ruby\nconfig_filename = options[:config_file_path] || \"config.yml\"\n```\n\nAs well as add configuration file locations to search in:\n\n```ruby\nconfig.append_path Dir.pwd\nconfig.append_path Dir.home\n```\n\nOnce config is initialized, you can read the configuration from a config file:\n\n```ruby\nbegin\n  config.read(config_filename)  # by default the \"config.yml\" is read\nrescue TTY::Config::ReadError =\u003e read_error\n  STDERR.puts \"\\nNo configuration file found:\"\n  STDERR.puts read_error\nend\n```\n\nThen merge options passed as arguments with those stored in a configuration file:\n\n```ruby\nconfig.merge(options)\n```\n\nProvide optional validation to ensure both host and port are configured:\n\n```ruby\nif !config.fetch(:host) || !config.fetch(:port)\n  STDERR.puts \"Host and port have to be specified (call with --help for help).\"\n  exit 1\nend\n```\n\n## Development\n\nAfter checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.\n\nTo install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/piotrmurach/tty-config. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n\n## Code of Conduct\n\nEveryone interacting in the TTY::Config project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/piotrmurach/tty-config/blob/master/CODE_OF_CONDUCT.md).\n\n## Copyright\n\nCopyright (c) 2018 Piotr Murach. See LICENSE for further details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpiotrmurach%2Ftty-config","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpiotrmurach%2Ftty-config","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpiotrmurach%2Ftty-config/lists"}