Sha256: a01662b1343927c3bf9e01f89e608b9b22686614c9725ba056eb5d369b968dcf

Contents?: true

Size: 1.35 KB

Versions: 6

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

module Html2rss
  module ItemExtractors
    ##
    # Returns the value of the attribute.
    #
    # Imagine this +time+ HTML tag with a +datetime+ attribute:
    #
    #     <time datetime="2019-07-01">...</time>
    #
    # YAML usage example:
    #
    #    selectors:
    #      link:
    #        selector: time
    #        extractor: attribute
    #        attribute: datetime
    #
    # Would return:
    #    '2019-07-01'
    #
    # In case you're extracting a date or a time, consider parsing it
    # during post processing with {AttributePostProcessors::ParseTime}.
    class Attribute
      # The available options for the attribute extractor.
      Options = Struct.new('AttributeOptions', :selector, :attribute, keyword_init: true)

      ##
      # Initializes the Attribute extractor.
      #
      # @param xml [Nokogiri::XML::Element]
      # @param options [Options]
      def initialize(xml, options)
        @options = options
        @element = ItemExtractors.element(xml, options.selector)
      end

      ##
      # Retrieves and returns the attribute's value as a string.
      #
      # @return [String] The value of the attribute.
      def get
        @element.attr(@options.attribute).to_s.freeze
      rescue NoMethodError => error
        raise "Failed to extract attribute: #{error.message}"
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
html2rss-0.15.0 lib/html2rss/item_extractors/attribute.rb
html2rss-0.14.0 lib/html2rss/item_extractors/attribute.rb
html2rss-0.13.0 lib/html2rss/item_extractors/attribute.rb
html2rss-0.12.0 lib/html2rss/item_extractors/attribute.rb
html2rss-0.11.0 lib/html2rss/item_extractors/attribute.rb
html2rss-0.10.0 lib/html2rss/item_extractors/attribute.rb