|
2 | 2 |
|
3 | 3 | module Immoscout |
4 | 4 | # The configuration object of the +immoscout+ gem. |
5 | | - class Configuration |
6 | | - include ActiveSupport::Configurable |
| 5 | + class Configuration < ActiveSupport::OrderedOptions |
| 6 | + # Track our configurations settings (+Symbol+ keys) and their defaults as |
| 7 | + # lazy-loaded +Proc+'s values |
| 8 | + class_attribute :defaults, |
| 9 | + instance_reader: true, |
| 10 | + instance_writer: false, |
| 11 | + instance_predicate: false, |
| 12 | + default: {} |
| 13 | + |
| 14 | + # Create a new +Configuration+ instance with all settings populated with |
| 15 | + # their respective defaults. |
| 16 | + # |
| 17 | + # @param args [Hash{Symbol => Mixed}] additional settings which |
| 18 | + # overwrite the defaults |
| 19 | + # @return [Configuration] the new configuration instance |
| 20 | + def initialize(**args) |
| 21 | + super() |
| 22 | + defaults.each { |key, default| self[key] = instance_exec(&default) } |
| 23 | + merge!(**args) |
| 24 | + end |
| 25 | + |
| 26 | + # A simple DSL method to define new configuration accessors/settings with |
| 27 | + # their defaults. The defaults can be retrieved with |
| 28 | + # +Configuration.defaults+ or +Configuration.new.defaults+. |
| 29 | + # |
| 30 | + # @param name [Symbol, String] the name of the configuration |
| 31 | + # accessor/setting |
| 32 | + # @param default [Mixed, nil] a non-lazy-loaded static value, serving as a |
| 33 | + # default value for the setting |
| 34 | + # @param block [Proc] when given, the default value will be lazy-loaded |
| 35 | + # (result of the Proc) |
| 36 | + def self.config_accessor(name, default = nil, &block) |
| 37 | + # Save the given configuration accessor default value |
| 38 | + defaults[name.to_sym] = block || -> { default } |
| 39 | + |
| 40 | + # Compile reader/writer methods so we don't have to go through |
| 41 | + # +ActiveSupport::OrderedOptions#method_missing+. |
| 42 | + define_method(name) { self[name] } |
| 43 | + define_method("#{name}=") { |value| self[name] = value } |
| 44 | + end |
7 | 45 |
|
8 | 46 | config_accessor(:consumer_key) { ENV.fetch('IMMOSCOUT_CONSUMER_KEY', nil) } |
9 | 47 | config_accessor(:consumer_secret) do |
|
0 commit comments