Class: RemoveDataAttributes::Processor

Inherits:
Object
  • Object
show all
Defined in:
lib/remove_data_attributes/processor.rb

Constant Summary collapse

DATA_ATTRIBUTE_KEYS =
["data", :data].freeze
DATA_ATTRIBUTE_PATTERN =
/\Adata-(?<attribute_name>.+)\z/

Instance Method Summary collapse

Constructor Details

#initialize(data_attributes) ⇒ Processor

Returns a new instance of Processor.



12
13
14
15
16
17
18
19
20
# File 'lib/remove_data_attributes/processor.rb', line 12

def initialize(data_attributes)
  valid_attribute_names = Array(data_attributes)
    .map(&DATA_ATTRIBUTE_PATTERN.method(:match))
    .select(&:itself)
    .map { |md| md[:attribute_name] }

  @target_keys = valid_attribute_names.map { |name| "data-#{name}" }.to_set
  @target_keys_in_nested_hash = valid_attribute_names.map(&method(:normalize)).to_set
end

Instance Method Details

#call(hash) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/remove_data_attributes/processor.rb', line 22

def call(hash)
  new_hash = hash.reject { |key, _| @target_keys.include?(key.to_s) }

  DATA_ATTRIBUTE_KEYS.each do |key|
    nested_hash = hash[key]
    next unless nested_hash.is_a?(::Hash)

    new_hash[key] = nested_hash
      .reject { |key, _| @target_keys_in_nested_hash.include?(normalize(key)) }
  end

  new_hash
end