Class: ViewComponentReducible::Msg

Inherits:
Struct
  • Object
show all
Defined in:
lib/view_component_reducible/msg.rb,
lib/view_component_reducible/msg.rb

Overview

Message payload sent from the client.

Defined Under Namespace

Modules: Payload

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#payloadObject

Returns the value of attribute payload

Returns:

  • the current value of payload



7
8
9
# File 'lib/view_component_reducible/msg.rb', line 7

def payload
  @payload
end

#typeObject

Returns the value of attribute type

Returns:

  • the current value of type



7
8
9
# File 'lib/view_component_reducible/msg.rb', line 7

def type
  @type
end

Class Method Details

.build(type:, payload: nil) ⇒ ViewComponentReducible::Msg

Build a Msg with a normalized payload object.

Parameters:

  • (defaults to: nil)

Returns:



30
31
32
33
34
35
# File 'lib/view_component_reducible/msg.rb', line 30

def self.build(type:, payload: nil)
  return new(type:, payload:) if payload.is_a?(Data)

  normalized = normalize_type(type)
  new(type:, payload: self::Payload.from_hash(normalized, payload))
end

.from_params(params) ⇒ ViewComponentReducible::Msg

Build a Msg from request params.

Parameters:

Returns:



19
20
21
22
23
24
# File 'lib/view_component_reducible/msg.rb', line 19

def self.from_params(params)
  type = params.fetch('vcr_msg_type')
  payload_json = params['vcr_msg_payload']
  payload = payload_json && payload_json != '' ? JSON.parse(payload_json) : {}
  build(type:, payload:)
end

.normalize_type(type) ⇒ Symbol

Parameters:

Returns:



39
40
41
42
43
44
45
# File 'lib/view_component_reducible/msg.rb', line 39

def self.normalize_type(type)
  type.to_s
      .gsub(/([a-z\d])([A-Z])/, '\1_\2')
      .tr('-', '_')
      .downcase
      .to_sym
end

Instance Method Details

#deconstruct_keys(keys) ⇒ Hash{Symbol=>Object}

Enable pattern matching with normalized symbol types.

Parameters:

Returns:



11
12
13
14
# File 'lib/view_component_reducible/msg.rb', line 11

def deconstruct_keys(keys)
  payload_hash = { type: normalized_type, payload: payload }
  keys ? payload_hash.slice(*keys) : payload_hash
end