Class: Anyway::Config

Inherits:
Object
  • Object
show all
Includes:
DynamicConfig, OptparseConfig, Rails::Config
Defined in:
lib/anyway/config.rb

Overview

Base config class Provides ‘attr_config` method to describe configuration parameters and set defaults

Defined Under Namespace

Classes: BlockCallback, Error, NamedCallback, ValidationError

Constant Summary collapse

PARAM_NAME =
/^[a-z_](\w+)?$/
RESERVED_NAMES =

List of names that couldn’t be used as config names (the class instance methods we use)

%i[
  config_name
  env_prefix
  values
  class
  clear
  deconstruct_keys
  dig
  dup
  initialize
  load
  load_from_sources
  option_parser
  pretty_print
  raise_validation_error
  reload
  resolve_config_path
  tap
  to_h
  to_source_trace
  write_config_attr
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DynamicConfig

included

Methods included from OptparseConfig

included, #option_parser, #parse_options!

Constructor Details

#initialize(overrides = nil) ⇒ Config

Instantiate config instance.

Example:

my_config = Anyway::Config.new()

# provide some values explicitly
my_config = Anyway::Config.new({some: :value})

Raises:

  • (ArgumentError)


263
264
265
266
267
268
269
270
271
272
# File 'lib/anyway/config.rb', line 263

def initialize(overrides = nil)
  @config_name = self.class.config_name

  raise ArgumentError, "Config name is missing" unless @config_name

  @env_prefix = self.class.env_prefix
  @values = {}

  load(overrides)
end

Instance Attribute Details

#config_nameObject (readonly)

Returns the value of attribute config_name.



252
253
254
# File 'lib/anyway/config.rb', line 252

def config_name
  @config_name
end

#env_prefixObject (readonly)

Returns the value of attribute env_prefix.



252
253
254
# File 'lib/anyway/config.rb', line 252

def env_prefix
  @env_prefix
end

Class Method Details

.attr_config(*args, **hargs) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/anyway/config.rb', line 79

def attr_config(*args, **hargs)
  new_defaults = hargs.deep_dup
  new_defaults.stringify_keys!

  defaults.merge! new_defaults

  new_keys = ((args + new_defaults.keys) - config_attributes)

  validate_param_names! new_keys.map(&:to_s)

  new_keys.map!(&:to_sym)

  unless (reserved_names = (new_keys & RESERVED_NAMES)).empty?
    raise ArgumentError, "Can not use the following reserved names as config attrubutes: " \
      "#{reserved_names.sort.map(&:to_s).join(", ")}"
  end

  config_attributes.push(*new_keys)

  define_config_accessor(*new_keys)

  # Define predicate methods ("param?") for attributes
  # having `true` or `false` as default values
  new_defaults.each do |key, val|
    next unless val.is_a?(TrueClass) || val.is_a?(FalseClass)
    alias_method :"#{key}?", :"#{key}"
  end
end

.config_attributesObject



118
119
120
121
122
123
124
125
126
# File 'lib/anyway/config.rb', line 118

def config_attributes
  return @config_attributes if instance_variable_defined?(:@config_attributes)

  @config_attributes = if superclass < Anyway::Config
    superclass.config_attributes.dup
  else
    []
  end
end

.config_name(val = nil) ⇒ Object



166
167
168
169
170
171
172
# File 'lib/anyway/config.rb', line 166

def config_name(val = nil)
  return (@explicit_config_name = val.to_s) unless val.nil?

  return @config_name if instance_variable_defined?(:@config_name)

  @config_name = explicit_config_name || build_config_name
end

.defaultsObject



108
109
110
111
112
113
114
115
116
# File 'lib/anyway/config.rb', line 108

def defaults
  return @defaults if instance_variable_defined?(:@defaults)

  @defaults = if superclass < Anyway::Config
    superclass.defaults.deep_dup
  else
    new_empty_config
  end
end

.env_prefix(val = nil) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
# File 'lib/anyway/config.rb', line 185

def env_prefix(val = nil)
  return (@env_prefix = val.to_s.upcase) unless val.nil?

  return @env_prefix if instance_variable_defined?(:@env_prefix)

  @env_prefix = if superclass < Anyway::Config && superclass.explicit_config_name?
    superclass.env_prefix
  else
    config_name.upcase
  end
end

.explicit_config_nameObject



174
175
176
177
178
179
180
181
# File 'lib/anyway/config.rb', line 174

def explicit_config_name
  return @explicit_config_name if instance_variable_defined?(:@explicit_config_name)

  @explicit_config_name =
    if superclass.respond_to?(:explicit_config_name)
      superclass.explicit_config_name
    end
end

.explicit_config_name?Boolean

Returns:

  • (Boolean)


183
# File 'lib/anyway/config.rb', line 183

def explicit_config_name?() = !explicit_config_name.nil?

.load_callbacksObject



156
157
158
159
160
161
162
163
164
# File 'lib/anyway/config.rb', line 156

def load_callbacks
  return @load_callbacks if instance_variable_defined?(:@load_callbacks)

  @load_callbacks = if superclass <= Anyway::Config
    superclass.load_callbacks.dup
  else
    []
  end
end

.new_empty_configObject



197
# File 'lib/anyway/config.rb', line 197

def new_empty_config() = {}

.on_load(*names, &block) ⇒ Object

Raises:

  • (ArgumentError)


146
147
148
149
150
151
152
153
154
# File 'lib/anyway/config.rb', line 146

def on_load(*names, &block)
  raise ArgumentError, "Either methods or block should be specified, not both" if block && !names.empty?

  if block
    load_callbacks << BlockCallback.new(block)
  else
    load_callbacks.push(*names.map { NamedCallback.new(_1) })
  end
end

.required(*names) ⇒ Object



128
129
130
131
132
133
134
# File 'lib/anyway/config.rb', line 128

def required(*names)
  unless (unknown_names = (names - config_attributes)).empty?
    raise ArgumentError, "Unknown config param: #{unknown_names.join(",")}"
  end

  required_attributes.push(*names)
end

.required_attributesObject



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

def required_attributes
  return @required_attributes if instance_variable_defined?(:@required_attributes)

  @required_attributes = if superclass < Anyway::Config
    superclass.required_attributes.dup
  else
    []
  end
end

Instance Method Details

#clearObject



280
281
282
283
284
# File 'lib/anyway/config.rb', line 280

def clear
  values.clear
  @__trace__ = nil
  self
end

#deconstruct_keys(keys) ⇒ Object



344
# File 'lib/anyway/config.rb', line 344

def deconstruct_keys(keys) = values.deconstruct_keys(keys)

#dig(*keys) ⇒ Object



327
# File 'lib/anyway/config.rb', line 327

def dig(*keys) = values.dig(*keys)

#dupObject



331
332
333
334
335
336
337
338
# File 'lib/anyway/config.rb', line 331

def dup
  self.class.allocate.tap do |new_config|
    %i[config_name env_prefix __trace__].each do |ivar|
      new_config.instance_variable_set(:"@#{ivar}", send(ivar).dup)
    end
    new_config.instance_variable_set(:@values, values.deep_dup)
  end
end

#inspectObject



348
349
350
351
# File 'lib/anyway/config.rb', line 348

def inspect
  "#<#{self.class}:0x#{vm_object_id.rjust(16, "0")} config_name=\"#{config_name}\" env_prefix=\"#{env_prefix}\" " \
  "values=#{values.inspect}>"
end

#load(overrides = nil) ⇒ Object



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/anyway/config.rb', line 286

def load(overrides = nil)
  base_config = self.class.defaults.deep_dup

  trace = Tracing.capture do
    Tracing.trace!(:defaults) { base_config }

    config_path = resolve_config_path(config_name, env_prefix)

    load_from_sources(base_config, name: config_name, env_prefix:, config_path:)

    if overrides
      Tracing.trace!(:load) { overrides }

      Utils.deep_merge!(base_config, overrides)
    end
  end

  base_config.each do |key, val|
    write_config_attr(key.to_sym, val)
  end

  # Trace may contain unknown attributes
  trace&.keep_if { |key| self.class.config_attributes.include?(key.to_sym) }

  # Run on_load callbacks
  self.class.load_callbacks.each { _1.apply_to(self) }

  # Set trace after we write all the values to
  # avoid changing the source to accessor
  @__trace__ = trace

  self
end

#load_from_sources(base_config, **options) ⇒ Object



320
321
322
323
324
325
# File 'lib/anyway/config.rb', line 320

def load_from_sources(base_config, **options)
  Anyway.loaders.each do |(_id, loader)|
    Utils.deep_merge!(base_config, loader.call(**options))
  end
  base_config
end

#pretty_print(q) ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/anyway/config.rb', line 353

def pretty_print(q)
  q.object_group self do
    q.nest(1) do
      q.breakable
      q.text "config_name=#{config_name.inspect}"
      q.breakable
      q.text "env_prefix=#{env_prefix.inspect}"
      q.breakable
      q.text "values:"
      q.pp __trace__
    end
  end
end

#reload(overrides = nil) ⇒ Object



274
275
276
277
278
# File 'lib/anyway/config.rb', line 274

def reload(overrides = nil)
  clear
  load(overrides)
  self
end

#resolve_config_path(name, env_prefix) ⇒ Object



340
341
342
# File 'lib/anyway/config.rb', line 340

def resolve_config_path(name, env_prefix)
  Anyway.env.fetch(env_prefix).delete("conf") || Settings.default_config_path.call(name)
end

#to_hObject



329
# File 'lib/anyway/config.rb', line 329

def to_h() = values.deep_dup.deep_freeze

#to_source_traceObject



346
# File 'lib/anyway/config.rb', line 346

def to_source_trace() = __trace__&.to_h