Module: ViewComponentReducible::Dispatch

Defined in:
lib/view_component_reducible/dispatch.rb

Overview

Helpers for dispatch responses.

Class Method Summary collapse

Class Method Details

.inject_state(html, signed_state) ⇒ String

Inject a signed state token into HTML.

Parameters:

Returns:



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/view_component_reducible/dispatch.rb', line 12

def self.inject_state(html, signed_state)
  meta = %(<meta name="vcr-state" content="#{ERB::Util.html_escape(signed_state)}">)
  script = <<~SCRIPT.chomp
    <script>
    (function() {
      var meta = document.querySelector('meta[name="vcr-state"]');
      if (!meta) return;
      var state = meta.getAttribute('content');
      var inputs = document.querySelectorAll('input[name="vcr_state"]');
      inputs.forEach(function(input) { input.value = state; });
    })();
    </script>
  SCRIPT

  injection = meta + script
  html.include?('</head>') ? html.sub('</head>', "#{injection}</head>") : (injection + html)
end