Class: Rack::DynamicConfigWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/dynamic_config_writer.rb

Constant Summary collapse

GLOBAL_ASSIGN =
"window.rackDynamicConfig"
BACKUP_SUFFIX =
".original"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(index_html_path, global_assign: GLOBAL_ASSIGN, backup_suffix: BACKUP_SUFFIX) ⇒ DynamicConfigWriter

Returns a new instance of DynamicConfigWriter.



28
29
30
31
32
33
34
35
36
# File 'lib/rack/dynamic_config_writer.rb', line 28

def initialize(
  index_html_path,
  global_assign: GLOBAL_ASSIGN,
  backup_suffix: BACKUP_SUFFIX
)
  @index_html_path = index_html_path.to_s
  @global_assign = global_assign
  @index_html_backup = @index_html_path + backup_suffix
end

Class Method Details

.pick_env(regex_or_prefix) ⇒ Object



69
70
71
72
# File 'lib/rack/dynamic_config_writer.rb', line 69

def self.pick_env(regex_or_prefix)
  return ENV.to_a.select { |(k, _v)| k.start_with?(regex_or_prefix) }.to_h if regex_or_prefix.is_a?(String)
  return ENV.to_a.select { |(k, _v)| regex_or_prefix.match?(k) }.to_h
end

Instance Method Details

#as_string(keys_and_values) ⇒ Object

Return the new index.html with dynamic config as a string.



55
56
57
58
59
# File 'lib/rack/dynamic_config_writer.rb', line 55

def as_string(keys_and_values)
  ::File.open(@index_html_path) do |f|
    return self.serialize(f, keys_and_values)
  end
end

#emplace(keys_and_values) ⇒ Object

Copy index_html_path to index.html.original (see BACKUP_SUFFIX), and add the dynamic config to index_html_path. Use as_string to avoid file writes.



41
42
43
44
45
46
47
# File 'lib/rack/dynamic_config_writer.rb', line 41

def emplace(keys_and_values)
  self.ensure_unmodified_html_backup
  ::File.open(@index_html_backup) do |f|
    new_html = self.serialize(f, keys_and_values)
    ::File.write(@index_html_path, new_html)
  end
end