Module: Coco::AlpineHelper

Includes:
ActionView::Helpers::JavaScriptHelper, TagHelper
Included in:
Component, Tag
Defined in:
app/helpers/coco/alpine_helper.rb

Instance Method Summary collapse

Methods included from TagHelper

#prefix_attr_keys, #random_id, #style_str

Instance Method Details

#x_attrs(attrs, root: false) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'app/helpers/coco/alpine_helper.rb', line 22

def x_attrs(attrs, root: false)
  attrs.symbolize_keys!

  if root && !attrs.key?(:data)
    attrs[:data] = "" # Add empty x-data attribute if none has been specified
  end

  attrs.transform_values! { (_1 == true) ? "" : _1 } # convert boolean x-attributes

  # prefix attributes where needed
  attrs.transform_keys do |key|
    key = key.to_s
    key.first.in?(["@", ":"]) ? key : "x-#{key}"
  end
end

#x_data(name = nil, data = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'app/helpers/coco/alpine_helper.rb', line 5

def x_data(name = nil, data = {})
  if name.is_a?(Hash)
    data = name
    name = nil
  end

  props_str = data.present? ? jsify_data(data) : nil

  expression = if name.present?
    "#{jsify_var_name(name)}#{"(#{props_str})" if props_str.present?}"
  else
    props_str
  end

  expression.html_safe
end