Sha256: 801035874d96d1f9a987342c053fb914b7f00fc480ecc5bdbebd22ff2398fbd4

Contents?: true

Size: 1.97 KB

Versions: 6

Compression:

Stored size: 1.97 KB

Contents

# frozen_string_literal: true

module ModsDisplay
  class NameFormatter
    def self.format(element)
      new(element).format
    end

    def initialize(element)
      @element = element
    end

    def format
      return element_text(display_form_nodeset) if display_form_nodeset.present?
      return name_parts if name_parts.present?

      nil
    end

    private

    attr_reader :element

    def name_parts
      @name_parts ||= begin
        output = [unqualified_name_parts(name_part_nodeset),
                  qualified_name_parts(name_part_nodeset, 'family'),
                  qualified_name_parts(name_part_nodeset, 'given')].flatten.compact.join(', ')
        terms = qualified_name_parts(name_part_nodeset, 'termsOfAddress')
        unless terms.empty?
          term_delimiter = ', '
          term_delimiter = ' ' if name_part_begins_with_roman_numeral?(terms.first)
          output = [output, terms.join(', ')].flatten.compact.join(term_delimiter)
        end
        dates = qualified_name_parts(name_part_nodeset, 'date')
        output = [output, dates].flatten.compact.join(', ') unless dates.empty?
        output
      end
    end

    def unqualified_name_parts(name_part_nodeset)
      name_part_nodeset.map do |part|
        element_text(part) unless part.attributes['type']
      end.compact
    end

    def qualified_name_parts(name_part_nodeset, type)
      name_part_nodeset.map do |part|
        element_text(part) if part.get_attribute('type') == type
      end.compact
    end

    def name_part_begins_with_roman_numeral?(part)
      first_part = part.split(/\s|,/).first.strip
      first_part.chars.all? do |char|
        %w[I X C L V].include? char
      end
    end

    def element_text(element)
      element.text.strip
    end

    def name_part_nodeset
      @name_part_nodeset ||= element.xpath('mods:namePart', mods: MODS_NS)
    end

    def display_form_nodeset
      @display_form_nodeset ||= element.xpath('mods:displayForm', mods: MODS_NS)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
mods_display-1.6.3 lib/mods_display/name_formatter.rb
mods_display-1.6.2 lib/mods_display/name_formatter.rb
mods_display-1.6.1 lib/mods_display/name_formatter.rb
mods_display-1.6.0 lib/mods_display/name_formatter.rb
mods_display-1.5.0 lib/mods_display/name_formatter.rb
mods_display-1.4.0 lib/mods_display/name_formatter.rb