Sha256: c0ed119800b7cabbeb6db71354c54a69fefcf35eb9b9785b7908ad07b2dd3d75

Contents?: true

Size: 1.87 KB

Versions: 5

Compression:

Stored size: 1.87 KB

Contents

# frozen_string_literal: true

module Kitchen
  # An element for a note
  #
  class NoteElement < ElementBase

    # Creates a new +NoteElement+
    #
    # @param node [Nokogiri::XML::Node] the node this element wraps
    # @param document [Document] this element's document
    #
    def initialize(node:, document: nil)
      super(node: node,
            document: document,
            enumerator_class: NoteElementEnumerator)
    end

    # Returns the short type
    # @return [Symbol]
    #
    def self.short_type
      :note
    end

    # Returns the note's title element
    #
    # @return [Element, nil]
    #
    def title
      block_error_if(block_given?)
      note_body = first('div.os-note-body')
      first_child = note_body ? note_body.element_children[0] : element_children[0]

      if first_child[:'data-type'] == 'title'
        first_child
      elsif first_child&.element_children&.[](0)&.[](:'data-type') == 'title'
        first_child.element_children[0]
      end
    end

    # Returns true if the note's title is autogenerated
    #
    # @return [Boolean]
    #
    def indicates_autogenerated_title?
      detected_note_title_key != 0 && detected_note_title_key.present?
    end

    # Get the autogenerated title for this note
    #
    # @return [String]
    #
    def autogenerated_title
      if indicates_autogenerated_title?
        I18n.t(:"notes.#{detected_note_title_key}")
      else
        "unknown title for note with classes #{classes}"
      end
    end

    protected

    def detected_note_title_key
      @detected_note_title_key ||= begin
        return 0 if classes.empty? || !I18n.t('.').key?(:notes)

        possible_keys = I18n.t(:notes).keys.map(&:to_s)
        keys = possible_keys & classes

        raise("too many translation keys: #{keys.join(', ')}") if keys.many?
        return 0 if keys.empty?

        keys.first
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
openstax_kitchen-12.0.0 lib/kitchen/note_element.rb
openstax_kitchen-11.2.0 lib/kitchen/note_element.rb
openstax_kitchen-11.1.0 lib/kitchen/note_element.rb
openstax_kitchen-11.0.0 lib/kitchen/note_element.rb
openstax_kitchen-10.0.0 lib/kitchen/note_element.rb