Module: ViewComponentReducible::Msg::Payload

Defined in:
lib/view_component_reducible/msg.rb

Defined Under Namespace

Classes: Empty, Value

Class Method Summary collapse

Class Method Details

.build_generic(payload_hash) ⇒ Object



68
69
70
71
72
73
74
75
# File 'lib/view_component_reducible/msg.rb', line 68

def self.build_generic(payload_hash)
  return Empty.new if payload_hash.empty?

  keys = payload_hash.keys.map(&:to_sym)
  klass = Data.define(*keys)
  values = keys.to_h { |key| [key, payload_hash[key.to_s]] }
  klass.new(**values)
end

.from_hash(_type, payload) ⇒ Object



59
60
61
62
63
64
65
66
# File 'lib/view_component_reducible/msg.rb', line 59

def self.from_hash(_type, payload)
  payload_hash = payload.is_a?(Hash) ? payload.transform_keys(&:to_s) : nil

  return Empty.new if payload.nil? || (payload.respond_to?(:empty?) && payload.empty?)
  return Value.new(value: payload) unless payload_hash

  build_generic(payload_hash)
end