Sha256: d42e150d77f7d81d377a3805f35f8e33fd3449724e7b6fe588c40e67c1f70ef9

Contents?: true

Size: 1.97 KB

Versions: 2

Compression:

Stored size: 1.97 KB

Contents

# frozen_string_literal: true

module MicroMicro
  module Parsers
    class ValueClassPatternParser
      # @see https://microformats.org/wiki/value-class-pattern#Basic_Parsing
      # @see https://microformats.org/wiki/value-class-pattern#Date_and_time_values
      HTML_ATTRIBUTES_MAP = {
        'alt'      => %w[area img],
        'value'    => %w[data],
        'title'    => %w[abbr],
        'datetime' => %w[del ins time]
      }.freeze

      # @param context [Nokogiri::XML::NodeSet, Nokogiri::XML::Element]
      # @param node_set [Nokogiri::XML::NodeSet]
      # @return [Nokogiri::XML::NodeSet]
      def self.node_set_from(context, node_set = Nokogiri::XML::NodeSet.new(context.document, []))
        context.each { |node| node_set_from(node, node_set) } if context.is_a?(Nokogiri::XML::NodeSet)

        if context.is_a?(Nokogiri::XML::Element) && !Helpers.ignore_node?(context)
          if Helpers.value_class_node?(context) || Helpers.value_title_node?(context)
            node_set << context
          else
            node_set_from(context.element_children, node_set)
          end
        end

        node_set
      end

      # @param node [Nokogiri::XML::Element]
      # @return [String, nil]
      def self.value_from(node)
        return node['title'] if Helpers.value_title_node?(node)

        Helpers.attribute_value_from(node, HTML_ATTRIBUTES_MAP) || node.text
      end

      # @param context [Nokogiri::XML::Element]
      # @param separator [String]
      def initialize(node, separator = '')
        @node = node
        @separator = separator
      end

      # @return [String, nil]
      def value
        @value ||= values.join(separator).strip if values.any?
      end

      # @return [Array<String>]
      def values
        @values ||=
          self.class
              .node_set_from(node)
              .map { |value_node| self.class.value_from(value_node) }
              .select(&:present?)
      end

      private

      attr_reader :node, :separator
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
micromicro-2.0.1 lib/micro_micro/parsers/value_class_pattern_parser.rb
micromicro-2.0.0 lib/micro_micro/parsers/value_class_pattern_parser.rb