Class: Pulse::Component

Inherits:
ViewComponent::Base
  • Object
show all
Includes:
AttributesHelper, FetchOrFallbackHelper, SvgHelper
Defined in:
app/components/pulse/component.rb

Overview

This core Component class provides a place to include shared modules and helper methods that can be used by any child component.

Constant Summary collapse

TW_MERGE =
TailwindMerge::Merger.new(config: { prefix: 'pulse-' })

Constants included from AttributesHelper

AttributesHelper::PLURAL_ARIA_ATTRIBUTES, AttributesHelper::PLURAL_DATA_ATTRIBUTES

Class Method Summary collapse

Instance Method Summary collapse

Methods included from SvgHelper

#render_svg

Methods included from FetchOrFallbackHelper

#fetch_or_fallback, #fetch_or_fallback_boolean

Methods included from AttributesHelper

#aria, #data, #merge_aria, #merge_data, #merge_prefixed_attribute_hashes

Class Method Details

.generate_id(base_name: name.demodulize.underscore.dasherize) ⇒ Object



62
63
64
# File 'app/components/pulse/component.rb', line 62

def self.generate_id(base_name: name.demodulize.underscore.dasherize)
  "#{base_name}-#{SecureRandom.uuid}"
end

Instance Method Details

#merge_attributes(*args) ⇒ Object

Merge nested attributes together. Particularly helpful when combining data attributes without squashing previously existing data.

For example:

data = { data: { controller: "gallery" } }

@options[:data] = merge_attributes(
  data,
  action: "click->gallery#next",
)

Returns:

@options[:data]
  # => { controller: "gallery", action: "click->gallery#next" }


40
41
42
43
44
45
46
47
# File 'app/components/pulse/component.rb', line 40

def merge_attributes(*args)
  args = Array.new(2) { {} } if args.compact.blank?
  hashed_args = args.map { |el| el.presence || {} }

  hashed_args.first.deep_merge(hashed_args.second) do |_key, val, other_val|
    val + " #{other_val}"
  end
end

#merge_classes(*args) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/components/pulse/component.rb', line 49

def merge_classes(*args)
  args = args.compact_blank
  return '' if args.empty?

  classes = class_names(*args)
  return classes unless args.many?

  # Handle arbitrary variants, which `class_names` will escape
  classes = CGI.unescapeHTML(classes) if classes.include?('[&')

  TW_MERGE.merge(classes)
end