Module: Upkeep::Rails::ClientSubscription

Defined in:
lib/upkeep/rails/client_subscription.rb

Constant Summary collapse

CHANNEL =
"Upkeep::Rails::Cable::Channel"

Class Method Summary collapse

Class Method Details

.inject(html, identity:, subscription:) ⇒ Object



12
13
14
15
16
# File 'lib/upkeep/rails/client_subscription.rb', line 12

def inject(html, identity:, subscription:)
  marker = marker_for(identity: identity, subscription: subscription)
  insert_before_closing("body", html, marker) ||
    "#{html}#{marker}"
end

.insert_before_closing(tag, html, marker) ⇒ Object



37
38
39
40
41
42
# File 'lib/upkeep/rails/client_subscription.rb', line 37

def insert_before_closing(tag, html, marker)
  index = html.rindex(%(</#{tag}>)) || html.rindex(%(</#{tag.upcase}>))
  return unless index

  "#{html[0...index]}#{marker}#{html[index..]}"
end

.marker_for(identity:, subscription:) ⇒ Object

The payload travels as attributes (like turbo-cable-stream-source), never as text content, so it can't show up as page text when JS is absent.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/upkeep/rails/client_subscription.rb', line 20

def marker_for(identity:, subscription:)
  attributes = {
    "id" => "upkeep-subscription-source-#{subscription.id}",
    "channel" => CHANNEL,
    "subscription-id" => subscription.id,
    "activation-token" => ActivationToken.generate(subscription),
    "stream-name" => identity.stream_name
  }

  [
    %(<upkeep-subscription-source ),
    attributes.map { |name, value| %(#{name}="#{CGI.escapeHTML(value.to_s)}") }.join(" "),
    %( hidden style="display:none" data-upkeep-subscription data-turbo-temporary>),
    %(</upkeep-subscription-source>)
  ].join
end