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.

131 lines
4.4 KiB

  1. require 'dotenv'
  2. # FIXME: do not use global variable
  3. $definable_thread_group ||= ThreadGroup.new
  4. module Live
  5. # offers typed constant defintions with default value, by using lots of introspecting...
  6. module Definable
  7. MAIN_CSS = 'app/assets/stylesheets/application.css'.freeze # useful to trigger :reload_all from RailsLiveReload
  8. def integer(default = 0) = define_type_from_callee(caller[0], :integer, default)
  9. def boolean(default = true) = define_type_from_callee(caller[0], :boolean, default) # rubocop:disable Style/OptionalBooleanParameter
  10. def string(default = '') = define_type_from_callee(caller[0], :string, default)
  11. def reload_from_env
  12. logger.debug('reload from env')
  13. changes = []
  14. new_env_values = env_values(cached: false)
  15. new_env_keys = new_env_values.keys
  16. new_env_values.each_pair { |constant, raw| changes << override(constant, raw) }
  17. definitions.except(*new_env_keys).each_pair { |constant, definition| changes << restore(constant, definition) }
  18. changes.compact!
  19. trigger_rolling_event(changes) if changes.any?
  20. end
  21. private
  22. def trigger_rolling_event(changes)
  23. ActiveSupport::Notifications.instrument('rolling.live_constant', changes:)
  24. FileUtils.touch(MAIN_CSS) if defined?(RailsLiveReload) # triggering RailsLiveReload
  25. rescue StandardError => e
  26. logger.error(e)
  27. end
  28. def override(constant, raw)
  29. return unless definitions.include?(constant)
  30. type = definitions[constant][:type]
  31. new_value = typed_value(type, raw, definitions[constant][:default])
  32. old_value = definitions[constant][:value]
  33. return if new_value == old_value
  34. define_value(constant, new_value)
  35. logger.warn "Constant overriden from environment:#{Semantic::AnsiColors::CLEAR} #{constant} = #{new_value.ai}"
  36. { kind: :overriden, constant:, type:, old_value:, new_value: }
  37. end
  38. def restore(constant, definition)
  39. new_value = definition[:default]
  40. old_value = definition[:value]
  41. return if old_value == new_value
  42. type = definition[:type]
  43. define_value(constant, new_value)
  44. logger.warn "Constant restored:#{Semantic::AnsiColors::CLEAR} #{constant} = #{new_value.ai}"
  45. { kind: :restored, constant:, type:, old_value:, new_value: }
  46. end
  47. def env_values(cached: true)
  48. return @env_values if @env_values && cached
  49. @env_values = Dotenv.parse(*Dotenv::Rails.files)
  50. end
  51. def logger = @logger ||= SemanticLogger[self]
  52. def definitions = @definitions ||= {}
  53. def define_value(constant, value)
  54. definitions[constant][:value] = value
  55. remove_const(constant)
  56. const_set(constant, value)
  57. end
  58. # origin (or caller[0]) helps fetching the constant name from source code introspection
  59. def define_type_from_callee(origin, type, default)
  60. @@class_origin ||= self # rubocop:disable Style/ClassVars
  61. @listener ||= start_listener
  62. file, line = origin.split(':')
  63. constant = introspect_constant_from_file(file, line.to_i - 1)
  64. raw_value = env_values.fetch(constant, nil)
  65. value = typed_value(type, raw_value, default)
  66. definitions[constant] = { type:, default:, value: }
  67. # puts("-- new definition #{constant}:#{definitions[constant]}")
  68. value
  69. end
  70. def start_listener
  71. $definable_thread_group.list.each(&:kill)
  72. $definable_thread_group.add(Thread.new do
  73. listener = Listen.to(Rails.root, only: /^\.env\.?/) do
  74. @@class_origin.reload_from_env
  75. rescue StandardError
  76. nil
  77. end
  78. listener.start
  79. end)
  80. end
  81. def typed_value(type, raw, default)
  82. return default if raw.nil?
  83. case type
  84. when :integer then raw.to_i
  85. when :boolean then raw.upcase == 'TRUE'
  86. else raw
  87. end
  88. end
  89. # returns current directory of this source code
  90. def dir_source_location
  91. return @dir_source_location if defined?(@dir_source_location)
  92. *paths, _ = Live.const_source_location(:Definable).first.split('/')
  93. @dir_source_location = paths.join('/')
  94. end
  95. def introspect_constant_from_file(file, line)
  96. *dir_file, _ = file.split('/')
  97. dir_file = dir_file.join('/')
  98. raise "unexpected directory: #{dir_file} != #{dir_source_location}" unless dir_file == dir_source_location
  99. @lines ||= File.readlines(file) # cached source code
  100. @lines[line].match(/\s*(.\w+)/)[1] # TODO: should be uppercase!
  101. end
  102. end
  103. end