Ruby SDK Reference
This documentation applies to the v7.x version of the ConfigCat Ruby SDK. For the documentation of the latest release, please refer to this page.
Getting started
1. Install ConfigCat SDK
gem install configcat
2. Import the package
require 'configcat'
3. Create the ConfigCat client with your SDK Key
client = ConfigCat.get('#YOUR-SDK-KEY#')
4. Get your setting value
is_my_awesome_feature_enabled = client.get_value('isMyAwesomeFeatureEnabled', false)
if is_my_awesome_feature_enabled
do_the_new_thing
else
do_the_old_thing
end
5. Stop ConfigCat client
You can safely shut down all clients at once or individually and release all associated resources on application exit.
ConfigCat.close_all # closes all clients
client.close # closes a specific client
Creating the ConfigCat Client
ConfigCat Client is responsible for:
- managing the communication between your application and ConfigCat servers.
- caching your setting values and feature flags.
- serving values quickly in a failsafe way.
ConfigCat.get('#YOUR-SDK-KEY#')
returns a client with default options.
Client options | Description | Default |
---|---|---|
base_url | Sets the CDN base url (forward proxy, dedicated subscription) from where the sdk will download the config JSON. | nil |
polling_mode | Sets the polling mode for the client. More about polling modes. | PollingMode.auto_poll |
config_cache | Sets a custom config cache implementation for the client. More about cache. | nil |
proxy_address | Sets custom proxy address for the client. More about proxy. | nil |
proxy_port | Sets custom proxy port for the client. More about proxy. | nil |
proxy_user | Sets custom proxy user for the client. More about proxy. | nil |
proxy_pass | Sets custom proxy password for the client. More about proxy. | nil |
open_timeout_seconds | The number of seconds to wait for the server to make the initial connection (i.e. completing the TCP connection handshake). | 10 |
read_timeout_seconds | The number of seconds to wait for the server to respond before giving up. | 30 |
flag_overrides | Local feature flag & setting overrides. More about feature flag overrides | nil |
data_governance | Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. More about Data Governance. Available options: GLOBAL , EU_ONLY . | GLOBAL |
default_user | Sets the default user. More about default user. | nil |
hooks | Used to subscribe events that the SDK sends in specific scenarios. More about hooks. | nil |
offline | Indicates whether the SDK should be initialized in offline mode. More about offline mode. | false |
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
polling_mode: ConfigCat::PollingMode.auto_poll
)
)
We strongly recommend you to use the ConfigCat Client as a Singleton object in your application.
The ConfigCat.get
static factory method constructs singleton client instances for your SDK keys.
These clients can be closed all at once with the ConfigCat.close_all
method or individually with client.close
.
Anatomy of get_value
Parameters | Description |
---|---|
key | REQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting. |
default_value | REQUIRED. This value will be returned in case of an error. |
user | Optional, User Object. Essential when using Targeting. Read more about Targeting. |
value = client.get_value(
'keyOfMySetting', # Setting Key
false, # Default value
ConfigCat::User.new('#UNIQUE-USER-IDENTIFIER#') # Optional User Object
);
Anatomy of get_value_details
get_value_details
is similar to get_value
but instead of returning the evaluated value only, it gives an EvaluationDetails
object with more detailed information about the evaluation result.
Parameters | Description |
---|---|
key | REQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting. |
default_value | REQUIRED. This value will be returned in case of an error. |
user | Optional, User Object. Essential when using Targeting. Read more about Targeting. |
details = client.get_value_details(
'keyOfMySetting', # Setting Key
false, # Default value
ConfigCat::User.new('#UNIQUE-USER-IDENTIFIER#') # Optional User Object
);
The details result contains the following information:
Property | Description |
---|---|
value | The evaluated value of the feature flag or setting. |
key | The key of the evaluated feature flag or setting. |
is_default_value | True when the default value passed to get_value_details() is returned due to an error. |
error | In case of an error, this field contains the error message. |
user | The User Object that was used for evaluation. |
matched_evaluation_percentage_rule | If the evaluation was based on a percentage rule, this field contains that specific rule. |
matched_evaluation_rule | If the evaluation was based on a Targeting Rule, this field contains that specific rule. |
fetch_time | The last download time (UTC Time) of the current config. |
User Object
The User Object is essential if you'd like to use ConfigCat's Targeting feature.
user_object = ConfigCat::User.new('#UNIQUE-USER-IDENTIFIER#')
user_object = ConfigCat::User.new('[email protected]')
Customized User Object creation
Parameters | Description |
---|---|
identifier | REQUIRED. Unique identifier of a user in your application. Can be any string value, even an email address. |
email | Optional parameter for easier Targeting Rule definitions. |
country | Optional parameter for easier Targeting Rule definitions. |
custom | Optional dictionary of strings representing the custom attributes of a user for advanced Targeting Rule definitions. e.g. User role, Subscription type. |
user_object = ConfigCat::User.new('#UNIQUE-USER-IDENTIFIER#', email: 'john@example', country: 'United Kingdom',
custom: {'SubscriptionType': 'Pro', 'UserRole': 'Admin'})
Default user
There's an option to set a default User Object that will be used at feature flag and setting evaluation. It can be useful when your application has a single user only, or rarely switches users.
You can set the default User Object either on SDK initialization:
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
default_user: ConfigCat::User.new('[email protected]')
)
)
or with the set_default_user
method of the ConfigCat client.
client.set_default_user(ConfigCat::User.new('[email protected]'))
Whenever the get_value
, get_value_details
, get_variation_id
, get_all_variation_ids
, or get_all_values
methods are called without an explicit user
parameter, the SDK will automatically use the default user as a User Object.
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
default_user: ConfigCat::User.new('[email protected]')
)
)
# The default user will be used at the evaluation process.
value = client.get_value('keyOfMySetting', false)
When the user
parameter is specified on the requesting method, it takes precedence over the default user.
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
default_user: ConfigCat::User.new('[email protected]')
)
)
other_user = ConfigCat::User.new('[email protected]')
# otherUser will be used at the evaluation process.
value = client.get_value('keyOfMySetting', false, other_user)
For deleting the default user, you can do the following:
client.clear_default_user
Polling Modes
The ConfigCat SDK supports 3 different polling mechanisms to acquire the setting values from ConfigCat. After latest setting values are downloaded, they are stored in the internal cache, then all get_value()
calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle.
More about polling modes.
Auto polling (default)
The ConfigCat SDK downloads the latest values and stores them automatically every 60 seconds.
Use the poll_interval_seconds
option parameter to change the polling interval.
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
polling_mode: ConfigCat::PollingMode.auto_poll(poll_interval_seconds: 95)
)
)
Available options:
Option Parameter | Description | Default |
---|---|---|
poll_interval_seconds | Polling interval. | 60 |
max_init_wait_time_seconds | Maximum waiting time between the client initialization and the first config acquisition in secconds. | 5 |
Lazy loading
When calling get_value
, the ConfigCat SDK downloads the latest setting values if they are not present or expired in the cache. In this case get_value
will return the setting value after the cache is updated.
Use cache_refresh_interval_seconds
option parameter to set cache lifetime.
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
polling_mode: ConfigCat::PollingMode.lazy_load(cache_refresh_interval_seconds: 600)
)
)
Available options:
Option Parameter | Description | Default |
---|---|---|
cache_refresh_interval_seconds | Cache TTL. | 60 |
Manual polling
Manual polling gives you full control over when the config JSON
(with the setting values) is downloaded. ConfigCat SDK will not update them automatically. Calling force_refresh
is your application's responsibility.
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
polling_mode: ConfigCat::PollingMode.manual_poll
)
)
client.force_refresh
get_value
returnsdefault_value
if the cache is empty. Callforce_refresh
to update the cache.
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
polling_mode: ConfigCat::PollingMode.manual_poll
)
)
value = client.get_value("key", "my default value") # Returns "my default value"
client.force_refresh
value = client.get_value("key", "my default value") # Returns "value from server"
Hooks
With the following hooks you can subscribe to particular events fired by the SDK:
-
on_client_ready
: This event is sent when the SDK reaches the ready state. If the SDK is set up with lazy load or manual polling it's considered ready right after instantiation. If it's using auto polling, the ready state is reached when the SDK has a valid config JSON loaded into memory either from cache or from HTTP. If the config couldn't be loaded neither from cache nor from HTTP theon_client_ready
event fires when the auto polling'smax_init_wait_time_seconds
is reached. -
on_config_changed(config: Hash)
: This event is sent when the SDK loads a valid config JSON into memory from cache, and each subsequent time when the loaded config JSON changes via HTTP. -
on_flag_evaluated(evaluation_details: EvaluationDetails)
: This event is sent each time when the SDK evaluates a feature flag or setting. The event sends the same evaluation details that you would get fromget_value_details
. -
on_error(error: String)
: This event is sent when an error occurs within the ConfigCat SDK.
You can subscribe to these events either on SDK initialization:
def on_flag_evaluated(evaluation_details)
# handle the event
end
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
hooks: ConfigCat::Hooks.new(on_flag_evaluated: method(:on_flag_evaluated))
)
)
or with the hooks
property of the ConfigCat client:
client.hooks.add_on_flag_evaluated(method(:on_flag_evaluated))
Online / Offline mode
In cases when you'd want to prevent the SDK from making HTTP calls, you can put it in offline mode:
client.set_offline
In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.
To put the SDK back in online mode, you can do the following:
client.set_online
With
client.offline?
you can check whether the SDK is in offline mode.
Flag Overrides
With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:
-
Local only (
ConfigCat::OverrideBehaviour::LOCAL_ONLY
): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources. -
Local over remote (
ConfigCat::OverrideBehaviour::LOCAL_OVER_REMOTE
): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence. -
Remote over local (
ConfigCat::OverrideBehaviour::REMOTE_OVER_LOCAL
): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.
You can set up the SDK to load your feature flag & setting overrides from a file or a hash.
JSON File
The SDK can be load your feature flag & setting overrides from a file.
File
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
flag_overrides: ConfigCat::LocalFileFlagOverrides.new(
'path/to/the/local_flags.json', # path to the file
ConfigCat::OverrideBehaviour::LOCAL_ONLY
)
)
)
JSON File Structure
The SDK supports 2 types of JSON structures to describe feature flags & settings.
1. Simple (key-value) structure
{
"flags": {
"enabledFeature": true,
"disabledFeature": false,
"intSetting": 5,
"doubleSetting": 3.14,
"stringSetting": "test"
}
}
2. Complex (full-featured) structure
This is the same format that the SDK downloads from the ConfigCat CDN. It allows the usage of all features that are available on the ConfigCat Dashboard.
You can download your current config JSON from ConfigCat's CDN and use it as a baseline.
The URL to your current config JSON is based on your Data Governance settings:
- GLOBAL:
https://cdn-global.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v5.json
- EU:
https://cdn-eu.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v5.json
{
"f": {
// list of feature flags & settings
"isFeatureEnabled": {
// key of a particular flag
"v": false, // default value, served when no rules are defined
"i": "430bded3", // variation id (for analytical purposes)
"t": 0, // feature flag's type, possible values:
// 0 -> BOOLEAN
// 1 -> STRING
// 2 -> INT
// 3 -> DOUBLE
"p": [
// list of percentage rules
{
"o": 0, // rule's order
"v": true, // value served when the rule is selected during evaluation
"p": 10, // % value
"i": "bcfb84a7" // variation id (for analytical purposes)
},
{
"o": 1, // rule's order
"v": false, // value served when the rule is selected during evaluation
"p": 90, // % value
"i": "bddac6ae" // variation id (for analytical purposes)
}
],
"r": [
// list of Targeting Rules
{
"o": 0, // rule's order
"a": "Identifier", // comparison attribute
"t": 2, // comparator, possible values:
// 0 -> 'IS ONE OF',
// 1 -> 'IS NOT ONE OF',
// 2 -> 'CONTAINS',
// 3 -> 'DOES NOT CONTAIN',
// 4 -> 'IS ONE OF (SemVer)',
// 5 -> 'IS NOT ONE OF (SemVer)',
// 6 -> '< (SemVer)',
// 7 -> '<= (SemVer)',
// 8 -> '> (SemVer)',
// 9 -> '>= (SemVer)',
// 10 -> '= (Number)',
// 11 -> '<> (Number)',
// 12 -> '< (Number)',
// 13 -> '<= (Number)',
// 14 -> '> (Number)',
// 15 -> '>= (Number)',
// 16 -> 'IS ONE OF (Hashed)',
// 17 -> 'IS NOT ONE OF (Hashed)'
"c": "@example.com", // comparison value
"v": true, // value served when the rule is selected during evaluation
"i": "bcfb84a7" // variation id (for analytical purposes)
}
]
}
}
}
Hash
You can set up the SDK to load your feature flag & setting overrides from a hash.
dictionary = {
"enabledFeature" => true,
"disabledFeature" => false,
"intSetting" => 5,
"doubleSetting" => 3.14,
"stringSetting" => "test"
}
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
flag_overrides: ConfigCat::LocalDictionaryFlagOverrides.new(dictionary, ConfigCat::OverrideBehaviour::LOCAL_ONLY)
)
)
Logging
In the ConfigCat SDK, a default logger writes logs to the standard output. The following example shows how to set the Log Level of the default logger.
ConfigCat.logger.level = Logger::INFO
Available log levels:
Level | Description |
---|---|
ERROR | Only error level events are logged. |
WARN | Default. Errors and Warnings are logged. |
INFO | Errors, Warnings and feature flag evaluation is logged. |
DEBUG | All of the above plus debug info is logged. Debug logs can be different for other SDKs. |
Info level logging helps to inspect the feature flag evaluation process:
INFO -- : Evaluating get_value('isPOCFeatureEnabled').
User object:
{
"Identifier" : "#UNIQUE-USER-IDENTIFIER#",
"Email" : "[email protected]"
}
Evaluating rule: [Email] [CONTAINS] [@something.com] => no match
Evaluating rule: [Email] [CONTAINS] [@example.com] => match, returning: true
You can easily replace the default logger with your own one. The following example shows how to set a logger writes logs into a text file.
ConfigCat.logger = Logger.new('log.txt')
get_all_keys
You can query the keys from your config JSON in the SDK with the get_all_keys
method.
client = ConfigCat.get('#YOUR-SDK-KEY#')
keys = client.get_all_keys
get_all_values
Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.
Parameters | Description |
---|---|
user | Optional, User Object. Essential when using Targeting. Read more about Targeting. |
client = ConfigCat.get('#YOUR-SDK-KEY#')
setting_values = client.get_all_values(ConfigCat::User.new('#UNIQUE-USER-IDENTIFIER#')) # Optional User Object
get_all_value_details
Evaluates and returns the detailed values of all feature flags and settings. Passing a User Object is optional.
client = ConfigCat.get('#YOUR-SDK-KEY#')
all_value_details = client.get_all_value_details(ConfigCat::User.new('#UNIQUE-USER-IDENTIFIER#')) # Optional User Object
Custom cache
The ConfigCat SDK stores the downloaded config data in a local cache to minimize network traffic and enhance client performance.
If you prefer to use your own cache solution, such as an external or distributed cache in your system,
you can implement the ConfigCache
interface
and set the config_cache
parameter in the options passed to ConfigCat.get
.
This allows you to seamlessly integrate ConfigCat with your existing caching infrastructure.
You have the option to inject your custom cache implementation into the client. All you have to do is to inherit from the ConfigCache abstract class:
class InMemoryConfigCache < ConfigCat::ConfigCache
attr_reader :value
def initialize
@value = {}
end
def get(key)
# you should return the cached value
return @value.fetch(key, nil)
end
def set(key, value)
# you should cache the new value
@value[key] = value
end
end
Then use your custom cache implementation:
client = ConfigCat.get('#YOUR-SDK-KEY#',
ConfigCat::ConfigCatOptions.new(
config_cache: InMemoryConfigCache.new
)
)
The Ruby SDK supports shared caching. You can read more about this feature and the required minimum SDK versions here.
Force refresh
Call the force_refresh
method on the client to download the latest config JSON and update the cache.
Using ConfigCat behind a proxy
Provide your own network credentials (username/password), and proxy server settings (proxy server/port) by passing the proxy details to the creator method.
configcat_client = ConfigCat.get("#YOUR-SDK-KEY#",
ConfigCat::ConfigCatOptions.new(
proxy_address: "127.0.0.1",
proxy_port: 8080,
proxy_user: "user",
proxy_pass: "password"
)
)