Class: HasHelpers::LazyConfig
- Inherits:
-
Object
- Object
- HasHelpers::LazyConfig
- Defined in:
- lib/has_helpers/lazy_config.rb
Constant Summary collapse
- INVALID_INIT_PARAMS_ERR_MSG =
"Cannot give a LazyConfig both a file path and a block."
Instance Attribute Summary collapse
-
#config_source ⇒ Object
readonly
Returns the value of attribute config_source.
Instance Method Summary collapse
- #config ⇒ Object
-
#initialize(config_location = nil, &block) ⇒ LazyConfig
constructor
LazyConfig can take two different kinds of arguments when you initialize it You can pass in a string which is the path to a YML file (which is organized by environment) - i.e., the typical YML config files we have been using.
- #method_missing(method_name, *args, &block) ⇒ Object
Constructor Details
#initialize(config_location = nil, &block) ⇒ LazyConfig
LazyConfig can take two different kinds of arguments when you initialize it You can pass in a string which is the path to a YML file (which is organized by environment) - i.e., the typical YML config files we have been using. You can also give it a block that returns a hash of config properties. The purpose of the block usage is in case the config properties rely on classes or other data sources that might not be loaded at initializer time (so we can use a block to defer evaluation of the properties). Giving it both a string argument and a block will raise an error.
Examples: SendGridConf = ::HasHelpers::LazyConfig.new(File.dirname(FILE) + "/../sendgrid.yml")
- or - SomeConf = ::HasHelpers::LazyConfig.new do { setting_1: "a", setting_2: ::SomeClass.foo } end
25 26 27 28 29 30 31 32 33 |
# File 'lib/has_helpers/lazy_config.rb', line 25 def initialize(config_location = nil, &block) @config_source = if block_given? raise INVALID_INIT_PARAMS_ERR_MSG if config_location block else config_location end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args, &block) ⇒ Object
52 53 54 55 56 57 58 59 |
# File 'lib/has_helpers/lazy_config.rb', line 52 def method_missing(method_name, *args, &block) (class << self; self; end).class_eval do define_method method_name do |*a, &b| config.send(method_name, *a, &b) end end send(method_name, *args, &block) end |
Instance Attribute Details
#config_source ⇒ Object (readonly)
Returns the value of attribute config_source.
7 8 9 |
# File 'lib/has_helpers/lazy_config.rb', line 7 def config_source @config_source end |
Instance Method Details
#config ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/has_helpers/lazy_config.rb', line 35 def config @config ||= begin conf_hash = if config_source.is_a?(Proc) config_source.call else raw_config = ERB.new(File.read(config_source)).result YAML.safe_load( raw_config, permitted_classes: [], permitted_symbols: [], aliases: true )[::HasUtils::Env.current_environment] end OpenStruct.new(conf_hash) end end |