Class: Vident2::Stimulus::ClassMap

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

Overview

‘data-<ctrl>-<name>-class` fragment — a named CSS class set readable on the JS side as `this.<name>Class`. Renamed from v1’s ‘StimulusClass` (which collided with Ruby’s ‘Class` — uncomfortable to type in user code).

‘css` holds the final serialised string form (space-joined); the parser normalises String / Array-of-String / Array-of-anything inputs down to one shape so the Draft/Plan doesn’t have to care.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.normalize_css(input) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/vident2/stimulus/class_map.rb', line 41

def self.normalize_css(input)
  case input
  when String
    input.split(/\s+/).reject(&:empty?).join(" ")
  when Array
    input.map(&:to_s).reject(&:empty?).join(" ")
  else
    raise ::Vident2::ParseError, "ClassMap.parse: css must be a String or Array, got #{input.class}"
  end
end

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



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/vident2/stimulus/class_map.rb', line 22

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

.to_data_hash(maps) ⇒ Object



61
62
63
64
65
66
# File 'lib/vident2/stimulus/class_map.rb', line 61

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

Instance Method Details

#data_attribute_keyObject



54
# File 'lib/vident2/stimulus/class_map.rb', line 54

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

#to_data_pairObject



56
# File 'lib/vident2/stimulus/class_map.rb', line 56

def to_data_pair = [data_attribute_key, css]

#to_hObject Also known as: to_hash



58
# File 'lib/vident2/stimulus/class_map.rb', line 58

def to_h = {data_attribute_key => css}

#to_sObject



52
# File 'lib/vident2/stimulus/class_map.rb', line 52

def to_s = css