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.

142 lines
4.9 KiB

3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
3 months ago
  1. require 'dotenv'
  2. DEFINABLE_THREAD_GROUP ||= ThreadGroup.new # rubocop:disable Lint/OrAssignmentToConstant
  3. DEFINABLE_LISTENERS ||= [] # rubocop:disable Lint/OrAssignmentToConstant
  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. logger.info ' ', dimensions: Semantic::FancyDimensions.new(rails: '╔═╗', before: 1)
  24. changes.each do |change|
  25. kind = change[:kind]
  26. constant = change[:constant]
  27. value = change[:new_value]
  28. logger.warn "Constant #{kind}:#{Semantic::AnsiColors::CLEAR} #{constant} = #{value.ai}"
  29. end
  30. logger.info ' ', dimensions: Semantic::FancyDimensions.new(rails: '╚═╝')
  31. ActiveSupport::Notifications.instrument('rolling.live_constant', changes:)
  32. FileUtils.touch(MAIN_CSS) if defined?(RailsLiveReload) # triggering RailsLiveReload
  33. rescue StandardError => e
  34. logger.error(e)
  35. end
  36. def override(constant, raw)
  37. return unless definitions.include?(constant)
  38. type = definitions[constant][:type]
  39. new_value = typed_value(type, raw, definitions[constant][:default])
  40. old_value = definitions[constant][:value]
  41. return if new_value == old_value
  42. define_value(constant, new_value)
  43. { kind: :overriden, constant:, type:, old_value:, new_value: }
  44. end
  45. def restore(constant, definition)
  46. new_value = definition[:default]
  47. old_value = definition[:value]
  48. return if old_value == new_value
  49. type = definition[:type]
  50. define_value(constant, new_value)
  51. { kind: :restored, constant:, type:, old_value:, new_value: }
  52. end
  53. def env_values(cached: true)
  54. return @env_values if @env_values && cached
  55. @env_values = Dotenv.parse(*Dotenv::Rails.files)
  56. end
  57. def logger = @logger ||= SemanticLogger[to_s.underscore]
  58. def definitions = @definitions ||= {}
  59. def define_value(constant, value)
  60. definitions[constant][:value] = value
  61. remove_const(constant)
  62. const_set(constant, value)
  63. end
  64. # origin (or caller[0]) helps fetching the constant name from source code introspection
  65. def define_type_from_callee(origin, type, default)
  66. @@class_origin ||= self # rubocop:disable Style/ClassVars
  67. @listener ||= start_listener if defined?(Listen)
  68. file, line = origin.split(':')
  69. constant = introspect_constant_from_file(file, line.to_i - 1)
  70. raw_value = env_values.fetch(constant, nil)
  71. value = typed_value(type, raw_value, default)
  72. definitions[constant] = { type:, default:, value: }
  73. # logger.debug("new definition #{constant}:#{definitions[constant]}")
  74. value
  75. end
  76. def start_listener
  77. DEFINABLE_LISTENERS.each(&:stop) # FIXME: issue on stop after multiple reload!!! Learn mode about listener: #close
  78. DEFINABLE_LISTENERS.clear
  79. DEFINABLE_THREAD_GROUP.list.each(&:kill)
  80. DEFINABLE_THREAD_GROUP.add(Thread.new do
  81. listener = Listen.to(Rails.root, only: /^\.env\.?/) do
  82. @@class_origin.reload_from_env
  83. rescue StandardError
  84. nil
  85. end
  86. DEFINABLE_LISTENERS << listener
  87. listener.start
  88. end)
  89. end
  90. def typed_value(type, raw, default)
  91. return default if raw.nil?
  92. case type
  93. when :integer then raw.to_i
  94. when :boolean then raw.upcase == 'TRUE'
  95. else raw
  96. end
  97. end
  98. # returns current directory of this source code
  99. def dir_source_location
  100. return @dir_source_location if defined?(@dir_source_location)
  101. *paths, _ = Live.const_source_location(:Definable).first.split('/')
  102. @dir_source_location = paths.join('/')
  103. end
  104. def introspect_constant_from_file(file, line)
  105. *dir_file, _ = file.split('/')
  106. dir_file = dir_file.join('/')
  107. raise "unexpected directory: #{dir_file} != #{dir_source_location}" unless dir_file == dir_source_location
  108. @lines ||= File.readlines(file) # cached source code
  109. @lines[line].match(/\s*(.\w+)/)[1] # TODO: should be uppercase!
  110. end
  111. end
  112. end