Class: Vident2::Stimulus::Param

Inherits:
Literal::Data
  • Object
show all
Defined in:
lib/vident2/stimulus/param.rb

Overview

‘data-<ctrl>-<name>-param` fragment — same shape as Value, distinct semantics on the JS side (read via `event.params.<camel>`).

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.parse(*args, implied:, component_id: nil) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/vident2/stimulus/param.rb', line 18

def self.parse(*args, implied:, component_id: nil)
  case args
  in [Symbol => name_sym, raw]
    new(
      controller: implied,
      name: name_sym.to_s.dasherize,
      serialized: serialize(raw)
    )
  in [String => ctrl_path, Symbol => name_sym, raw]
    new(
      controller: Controller.parse(ctrl_path, implied: implied),
      name: name_sym.to_s.dasherize,
      serialized: serialize(raw)
    )
  else
    raise ::Vident2::ParseError, "Param.parse: invalid arguments #{args.inspect}"
  end
end

.serialize(raw) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/vident2/stimulus/param.rb', line 37

def self.serialize(raw)
  raise ::Vident2::ParseError, "Param.serialize: nil is not serializable — filter nil upstream" if raw.nil?
  case raw
  when Array, Hash then raw.to_json
  else raw.to_s
  end
end

.to_data_hash(params) ⇒ Object



54
55
56
57
58
59
# File 'lib/vident2/stimulus/param.rb', line 54

def self.to_data_hash(params)
  params.each_with_object({}) do |p, acc|
    key, str = p.to_data_pair
    acc[key] = str
  end
end

Instance Method Details

#data_attribute_keyObject



47
# File 'lib/vident2/stimulus/param.rb', line 47

def data_attribute_key = :"#{controller.name}-#{name}-param"

#to_data_pairObject



49
# File 'lib/vident2/stimulus/param.rb', line 49

def to_data_pair = [data_attribute_key, serialized]

#to_hObject Also known as: to_hash



51
# File 'lib/vident2/stimulus/param.rb', line 51

def to_h = {data_attribute_key => serialized}

#to_sObject



45
# File 'lib/vident2/stimulus/param.rb', line 45

def to_s = serialized