Class: InertiaRails::MetaTag

Inherits:
Object
  • Object
show all
Defined in:
lib/inertia_rails/meta_tag.rb

Constant Summary collapse

UNARY_TAGS =
%i[
  area base br col embed hr img input keygen link meta source track wbr
].freeze
LD_JSON_TYPE =
'application/ld+json'
DEFAULT_SCRIPT_TYPE =
'text/plain'
GENERATABLE_HEAD_KEY_PROPERTIES =
%i[name property http_equiv].freeze

Instance Method Summary collapse

Constructor Details

#initialize(tag_name: nil, head_key: nil, allow_duplicates: false, type: nil, **tag_data) ⇒ MetaTag

Returns a new instance of MetaTag.



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/inertia_rails/meta_tag.rb', line 15

def initialize(tag_name: nil, head_key: nil, allow_duplicates: false, type: nil, **tag_data)
  if shortened_title_tag?(tag_name, tag_data)
    @tag_name = :title
    @tag_data = { inner_content: tag_data[:title] }
  else
    @tag_name = tag_name.nil? ? :meta : tag_name.to_sym
    @tag_data = tag_data.symbolize_keys
  end
  @tag_type = determine_tag_type(type)
  @allow_duplicates = allow_duplicates
  @head_key = @tag_name == :title ? 'title' : (head_key || generate_head_key)
end

Instance Method Details

#[](key) ⇒ Object



56
57
58
59
60
61
62
63
# File 'lib/inertia_rails/meta_tag.rb', line 56

def [](key)
  key = key.to_sym
  return @tag_name if key == :tag_name
  return @head_key if key == :head_key
  return @tag_type if key == :type

  @tag_data[key]
end

#as_json(_options = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/inertia_rails/meta_tag.rb', line 28

def as_json(_options = nil)
  {
    tagName: @tag_name,
    headKey: @head_key,
    type: @tag_type,
  }.tap do |result|
    result.merge!(@tag_data.transform_keys { |k| k.to_s.camelize(:lower).to_sym })
    result.compact_blank!
  end
end

#to_tag(tag_helper) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/inertia_rails/meta_tag.rb', line 39

def to_tag(tag_helper)
  data = @tag_data.merge(type: @tag_type, inertia: @head_key)

  inner_content =
    if @tag_name == :script
      tag_script_inner_content(data.delete(:inner_content))
    else
      data.delete(:inner_content)
    end

  if UNARY_TAGS.include? @tag_name
    tag_helper.public_send(@tag_name, **data.transform_keys { |k| k.to_s.tr('_', '-').to_sym })
  else
    tag_helper.public_send(@tag_name, inner_content, **data.transform_keys { |k| k.to_s.tr('_', '-').to_sym })
  end
end