Sha256: f3afeb173c85139b1f8d17a266b01dc54476f5dda344d0755d171d3b1b1de42a

Contents?: true

Size: 1.37 KB

Versions: 3

Compression:

Stored size: 1.37 KB

Contents

# frozen_string_literal: true

module Navigator
  # Renders a HTML tag.
  class Tag
    attr_reader :name, :content

    def self.names_without_suffix
      %w[img input]
    end

    # rubocop:disable Metrics/ParameterLists
    def initialize name, content = nil, attributes: {}, activator: Navigator::TagActivator.new
      @name = String(name)
      @content = content
      @attributes = attributes.with_indifferent_access
      @activator = activator
    end
    # rubocop:enable Metrics/ParameterLists

    def prefix
      ["<#{name}", format_attributes, ">"].compact * ""
    end

    def computed_content
      self.class.names_without_suffix.include?(name) ? nil : content
    end

    def suffix
      self.class.names_without_suffix.include?(name) ? nil : "</#{name}>"
    end

    def render
      [prefix, computed_content, suffix].compact * ""
    end

    private

    attr_reader :attributes, :activator

    def expand_data_attributes! attrs
      return unless attrs.key? :data
      attrs.delete(:data).each { |key, value| attrs["data-#{key}"] = value }
    end

    def concatenate_attributes attrs
      activator.activate(attrs).map { |key, value| %(#{key}="#{value}") } * " "
    end

    def format_attributes
      attrs = attributes.clone
      expand_data_attributes! attrs
      attrs = concatenate_attributes attrs
      attrs.empty? ? nil : " #{attrs}"
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
navigator-3.2.0 lib/navigator/tag.rb
navigator-3.1.0 lib/navigator/tag.rb
navigator-3.0.0 lib/navigator/tag.rb