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.

137 lines
4.6 KiB

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