Method: OpenCensus::Common::Config#add_option!

Defined in:
lib/opencensus/common/config.rb

#add_option!(key, initial = nil, opts = {}, &block) ⇒ Config

Add an option field to this configuration.

You must provide a key, which becomes the field name in this config. Field names may comprise only letters, numerals, and underscores, and must begin with a letter. This will create accessor methods for the new configuration key.

You may pass an initial value (which defaults to nil if not provided).

You may also specify how values are validated. Validation is defined as follows:

  • If you provide a block or a :validator option, it is used as the validator. A proposed value is passed to the proc, and it should return true or false to indicate whether the value is acceptable.
  • If you provide a :match option, it is compared to the proposed value using the === operator. You may, for example, provide a class, a regular expression, or a range. If you pass an array, the value is accepted if any of the elements match.
  • If you provide an :enum option, it should be an Enumerable. A proposed value is accepted if it is included.
  • Otherwise if you do not provide any of the above options, then a default validation strategy is inferred from the initial value:
    • If the initial is true or false, then either boolean value is considered valid. This is the same as enum: [true, false].
    • If the initial is nil, then any object is considered valid.
    • Otherwise, any object of the same class as the initial value is considered valid. This is effectively the same as match: initial.class.
  • You may also provide the :allow_nil option, which, if set to true, alters any of the above validators to allow nil values. If the initial value is nil but a specific validator is provided via :match or :enum, then :allow_nil defaults to true, otherwise it defaults to false.

In many cases, you may find that the default validation behavior (interpreted from the initial value) is sufficient. If you want to accept any value, use match: Object.

Parameters:

  • key (String, Symbol)

    The name of the option

  • initial (Object) (defaults to: nil)

    Initial value (defaults to nil)

  • opts (Hash) (defaults to: {})

    Validation options

Returns:

  • (Config)

    self for chaining



136
137
138
139
140
141
142
143
144
145
# File 'lib/opencensus/common/config.rb', line 136

def add_option! key, initial = nil, opts = {}, &block
  key = validate_new_key! key
  opts[:validator] = block if block
  validator = resolve_validator! initial, opts
  validate_value! key, validator, initial
  @fields[key] = Option.new initial, initial, validator
  define_getter_method! key
  define_setter_method! key
  self
end