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.

138 lines
4.7 KiB

2 months ago
2 months ago
2 months ago
  1. require 'dotenv'
  2. # DEFINABLE_THREAD_GROUP ||= ThreadGroup.new
  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)
  78. DEFINABLE_LISTENERS.clear
  79. listener = Listen.to(Rails.root, only: /^\.env\.?/) do
  80. @@class_origin.reload_from_env
  81. rescue StandardError => e
  82. logger.error('unable to reload from env', e)
  83. end
  84. listener.start
  85. DEFINABLE_LISTENERS << listener
  86. end
  87. def typed_value(type, raw, default)
  88. return default if raw.nil?
  89. case type
  90. when :integer then raw.to_i
  91. when :boolean then raw.upcase == 'TRUE'
  92. else raw
  93. end
  94. end
  95. # returns current directory of this source code
  96. def dir_source_location
  97. return @dir_source_location if defined?(@dir_source_location)
  98. *paths, _ = Live.const_source_location(:Definable).first.split('/')
  99. @dir_source_location = paths.join('/')
  100. end
  101. def introspect_constant_from_file(file, line)
  102. *dir_file, _ = file.split('/')
  103. dir_file = dir_file.join('/')
  104. raise "unexpected directory: #{dir_file} != #{dir_source_location}" unless dir_file == dir_source_location
  105. @lines ||= File.readlines(file) # cached source code
  106. @lines[line].match(/\s*(.\w+)/)[1] # TODO: should be uppercase!
  107. end
  108. end
  109. end