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.

55 lines
1.6 KiB

4 months ago
4 months ago
4 months ago
3 months ago
4 months ago
3 months ago
4 months ago
3 months ago
3 months ago
3 months ago
4 months ago
3 months ago
3 months ago
4 months ago
4 months ago
4 months ago
4 months ago
  1. require 'dotenv'
  2. # Hot Live Constants
  3. module HotConstants
  4. HOTENV = {} # rubocop:disable Style/MutableConstant
  5. LISTENERS = {} # rubocop:disable Style/MutableConstant
  6. LOGGER = SemanticLogger[to_s]
  7. class << self
  8. def initialize
  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. end
  17. def reload!
  18. HOTENV.replace Dotenv.parse # TODO: detect true changes before processing block below (or yield)
  19. LISTENERS.each_pair do |key, block|
  20. perform_change(key, block)
  21. end
  22. end
  23. def on_change(key, &block)
  24. LISTENERS[key.downcase.to_sym] = block
  25. perform_change(key, block)
  26. end
  27. private
  28. def perform_change(key, block)
  29. old_value = nil # TODO: remember last previous value
  30. new_value = method(key).call
  31. block.call(new_value, old_value)
  32. end
  33. def load_boolean(key, default) = HOTENV.fetch(key, default).to_s.downcase == 'true'
  34. def load_integer(key, default) = HOTENV.fetch(key, default).to_i
  35. def load_string(key, default) = HOTENV.fetch(key, default)
  36. def method_from_value(value)
  37. case value.downcase
  38. when /^(true|false)$/ then method(:load_boolean)
  39. when /^\d+$/ then method(:load_integer)
  40. else method(:load_string)
  41. end
  42. end
  43. end
  44. # initialize on first require
  45. initialize
  46. end