Sha256: 53ce59d1f79e542a75c6221a927f023ac43d9a57c441c428e4d80e5fd5d621b0

Contents?: true

Size: 1.37 KB

Versions: 14

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

14 entries across 14 versions & 1 rubygems

Version Path
navigator-6.0.2 lib/navigator/tag.rb
navigator-6.0.1 lib/navigator/tag.rb
navigator-6.0.0 lib/navigator/tag.rb
navigator-5.5.0 lib/navigator/tag.rb
navigator-5.4.0 lib/navigator/tag.rb
navigator-5.3.0 lib/navigator/tag.rb
navigator-5.2.0 lib/navigator/tag.rb
navigator-5.1.0 lib/navigator/tag.rb
navigator-5.0.0 lib/navigator/tag.rb
navigator-4.1.4 lib/navigator/tag.rb
navigator-4.1.3 lib/navigator/tag.rb
navigator-4.1.2 lib/navigator/tag.rb
navigator-4.1.1 lib/navigator/tag.rb
navigator-4.1.0 lib/navigator/tag.rb