Browse Source

on_change ok

main
pvincent 4 months ago
parent
commit
91ebf64c3f
  1. 2
      .env.sample
  2. 5
      config/initializers/hot_constants.rb
  3. 18
      lib/hot_constants/hot_constants.rb

2
.env.sample

@ -11,7 +11,7 @@
#-------------- #--------------
STIMULUS_DEBUG=false STIMULUS_DEBUG=false
LOG_ACTIVE_RECORD=false LOG_ACTIVE_RECORD=false
LOG_ACTION_VIEW=true
LOG_ACTION_VIEW=false
# INTEGER=2 # INTEGER=2
# STRING= # STRING=

5
config/initializers/hot_constants.rb

@ -3,6 +3,5 @@ return unless defined?(Rails::Server)
require Rails.root.join('lib', 'hot_constants', 'hot_constants') require Rails.root.join('lib', 'hot_constants', 'hot_constants')
HotConstants.initialize HotConstants.initialize
logger.info('hot constants initialized!')
# TODO: provide kind of a callback method which provides new value of hot constant change
HotConstants.on_change(:log_active_record) { |bool| ActiveRecord::Base.logger.level = bool ? :debug : :fatal }
HotConstants.on_change(:log_action_view) { |bool| ActionView::Base.logger.level = bool ? :debug : :fatal }

18
lib/hot_constants/hot_constants.rb

@ -7,6 +7,7 @@ module HotConstants
class << self class << self
def initialize def initialize
@on_change_listeners = {}
env_sample = Dotenv.parse('.env.sample') # TODO: able to detect add/remove, then either call define_method or undef_method! env_sample = Dotenv.parse('.env.sample') # TODO: able to detect add/remove, then either call define_method or undef_method!
env_sample.each do |key, value| env_sample.each do |key, value|
dkey = key.downcase dkey = key.downcase
@ -18,10 +19,16 @@ module HotConstants
end end
def reload! def reload!
HOTENV.replace Dotenv.parse # detect true changes before processing block below (or yield)
HOTENV.replace Dotenv.parse # TODO: detect true changes before processing block below (or yield)
@on_change_listeners.each_pair do |key, block|
old_value = nil # TODO: remember last previous value
new_value = method(key).call
block.call(new_value)
end
end
# TODO: replace with yield, thus externaliz process_block on behalf of HotEnv#initialize
process_block
def on_change(key, &block)
@on_change_listeners[key.downcase.to_sym] = block
end end
private private
@ -37,10 +44,5 @@ module HotConstants
else method(:load_string) else method(:load_string)
end end
end end
def process_block
ActiveRecord::Base.logger.level = log_active_record ? :debug : :fatal
ActionView::Base.logger.level = log_action_view ? :debug : :fatal
end
end end
end end
Loading…
Cancel
Save