Module: LiveCable::Connection::Messaging

Extended by:
ActiveSupport::Concern
Included in:
LiveCable::Connection
Defined in:
lib/live_cable/connection/messaging.rb

Instance Method Summary collapse

Instance Method Details

#action(component, data) ⇒ Boolean

Returns true when the message was processed, false when an error was handled (and an _error broadcast in its place).

Returns:

  • (Boolean)

    true when the message was processed, false when an error was handled (and an _error broadcast in its place)



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/live_cable/connection/messaging.rb', line 30

def action(component, data)
  params = parse_params(data)

  if data['_action']
    action = data['_action']&.to_sym

    if action == :_reactive
      return reactive(component, data)
    end

    unless component.class.allowed_actions.include?(action)
      raise LiveCable::Error, "Unauthorized action: #{action}"
    end

    method = component.method(action)

    if method.arity.positive?
      method.call(params)
    else
      method.call
    end
  end

  true
rescue StandardError => e
  handle_error(component, e)
  false
end

#reactive(component, data) ⇒ Boolean

Returns true when applied, false when an error was handled.

Returns:

  • (Boolean)

    true when applied, false when an error was handled



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/live_cable/connection/messaging.rb', line 60

def reactive(component, data)
  unless component.class.writable_reactive_variables.include?(data['name'].to_sym)
    raise LiveCable::Error, "Non-writable reactive variable: #{data['name']}"
  end

  component.public_send("#{data['name']}=", data['value'])

  true
rescue StandardError => e
  handle_error(component, e)
  false
end

#receive(component, data) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/live_cable/connection/messaging.rb', line 8

def receive(component, data)
  check_csrf_token(data)
  reset_changeset

  return unless data['messages'].present?

  # An error broadcasts an _error, which is itself the batch's one
  # response - so a failed message must suppress the trailing _ack
  errored = false
  data['messages'].each do |message|
    errored = true unless action(component, message)
  end

  rendered = broadcast_changeset

  # Guarantee exactly one response per message batch so the client can
  # clear its loading state even when nothing changed
  component.broadcast_ack unless errored || rendered.include?(component)
end