Class: Tailmix::HTML::DataMap

Inherits:
Object
  • Object
show all
Defined in:
lib/tailmix/html/data_map.rb

Constant Summary collapse

MERGEABLE_LIST_ATTRIBUTES =
i[controller action target].freeze

Instance Method Summary collapse

Constructor Details

#initialize(prefix, initial_data = {}) ⇒ DataMap

Returns a new instance of DataMap.



12
13
14
15
16
# File 'lib/tailmix/html/data_map.rb', line 12

def initialize(prefix, initial_data = {})
  @prefix = prefix
  @data = {}
  merge!(initial_data)
end

Instance Method Details

#add_to_set(key, value) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/tailmix/html/data_map.rb', line 45

def add_to_set(key, value)
  @data[key] ||= Set.new
  return unless value
  items_to_process = value.is_a?(Set) ? value.to_a : Array(value)
  items_to_process.each do |item|
    item.to_s.split.each do |token|
      @data[key].add(token) unless token.empty?
    end
  end
end

#merge(other_data) ⇒ Object



41
42
43
# File 'lib/tailmix/html/data_map.rb', line 41

def merge(other_data)
  dup.merge!(other_data)
end

#merge!(other_data) ⇒ Object Also known as: add



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/tailmix/html/data_map.rb', line 23

def merge!(other_data)
  return self unless other_data
  data_to_merge = other_data.is_a?(DataMap) ? other_data.instance_variable_get(:@data) : other_data

  (data_to_merge || {}).each do |key, value|
    key = key.to_sym
    if value.is_a?(Hash) && @data[key].is_a?(Hash)
      @data[key].merge!(value)
    elsif @prefix == "data" && MERGEABLE_LIST_ATTRIBUTES.include?(key)
      add_to_set(key, value)
    else
      @data[key] = value
    end
  end
  self
end

#remove(other_data) ⇒ Object



56
57
58
59
60
61
# File 'lib/tailmix/html/data_map.rb', line 56

def remove(other_data)
  (other_data || {}).each do |key, _|
    @data.delete(key.to_sym)
  end
  self
end

#stimulusObject



18
19
20
21
# File 'lib/tailmix/html/data_map.rb', line 18

def stimulus
  raise "Stimulus builder is only available for data attributes" unless @prefix == "data"
  StimulusBuilder.new(self)
end

#to_hObject



71
72
73
# File 'lib/tailmix/html/data_map.rb', line 71

def to_h
  flatten_data_hash(@data, @prefix)
end

#toggle(other_data) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/tailmix/html/data_map.rb', line 63

def toggle(other_data)
  (other_data || {}).each do |key, value|
    key = key.to_sym
    @data[key] == value ? @data.delete(key) : @data[key] = value
  end
  self
end