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
:validatoroption, 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
:matchoption, 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
:enumoption, it should be anEnumerable. 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
trueorfalse, then either boolean value is considered valid. This is the same asenum: [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.
- If the initial is
- You may also provide the
:allow_niloption, which, if set to true, alters any of the above validators to allownilvalues. If the initial value isnilbut a specific validator is provided via:matchor:enum, then:allow_nildefaults 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.
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 |