You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.5 KiB

3 months ago
3 months ago
3 months ago
3 months ago
2 months ago
2 months ago
3 months ago
2 months ago
3 months ago
2 months ago
3 months ago
3 months ago
3 months ago
  1. require 'dotenv'
  2. # Hot Live Constants
  3. module HotConstants
  4. HOTENV = {} # rubocop:disable Style/MutableConstant
  5. LOGGER = SemanticLogger[to_s]
  6. class << self
  7. def initialize
  8. @on_change_listeners = {}
  9. env_sample = Dotenv.parse('.env.sample') # TODO: able to detect add/remove, then either call define_method or undef_method!
  10. env_sample.each do |key, value|
  11. dkey = key.downcase
  12. method = method_from_value(value)
  13. singleton_class.define_method(dkey) { method.call(key, value) }
  14. LOGGER.info("create method <#{dkey}> performing <#{method.name}> with default value <#{value}> ")
  15. end
  16. reload!
  17. end
  18. def reload!
  19. HOTENV.replace Dotenv.parse # TODO: detect true changes before processing block below (or yield)
  20. @on_change_listeners.each_pair do |key, block|
  21. old_value = nil # TODO: remember last previous value
  22. new_value = method(key).call
  23. block.call(new_value)
  24. end
  25. end
  26. def on_change(key, &block)
  27. @on_change_listeners[key.downcase.to_sym] = block
  28. end
  29. private
  30. def load_boolean(key, default) = HOTENV.fetch(key, default).to_s.downcase == 'true'
  31. def load_integer(key, default) = HOTENV.fetch(key, default).to_i
  32. def load_string(key, default) = HOTENV.fetch(key, default)
  33. def method_from_value(value)
  34. case value.downcase
  35. when /^(true|false)$/ then method(:load_boolean)
  36. when /^\d+$/ then method(:load_integer)
  37. else method(:load_string)
  38. end
  39. end
  40. end
  41. end