Sha256: 15e0e52afdd4959accddddadfb82c76bd9d285d942d63229bb511ff849e01d4a

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

module Tolq::Parsers::Xliff
  class Parser

    # Creates a new Xliff parser
    #
    # @param quality [Symbol] the Tolq quality to order in, one of `:basic`, `:standard`, `:professional` or `:expert`
    # @return [Tolq::Parsers::Xliff::Parser] a parser ready to parse an xliff text
    def initialize(quality:, source_language_code: nil, target_language_code: nil)
      @quality = quality
      @source_language_code = source_language_code
      @target_language_code = target_language_code
    end

    # Parses an Xliff text
    #
    # @param xliff_text [String] the xlif format text to parse
    # @return [Hash] A hash suitable to be converted to json for the Tolq Api
    def parse(xliff_text)
      xliff = XLIFFer::XLIFF.new(xliff_text)
      file = xliff.files.first
      request_data = extract_request_data_from_file(file)

      {
        "request" => request_data,
        "source_language_code" => @source_language_code || strip_region_language(file.source_language),
        "target_language_code" => @target_language_code || strip_region_language(file.target_language),
        "quality" => @quality.to_s
      }
    end

    private

    def extract_request_data_from_file(xliff_file)
      xliff_file.strings.inject({}) do |acc, string|
        acc[string.id] = {"text" => string.source } if string.source && string.source.length > 0
        if string.note.length > 0
          acc[string.id].merge!("translator_message" => string.note)
        end
        acc
      end
    end

    def strip_region_language(language)
      language[0..1]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tolq-parsers-xliff-0.1.2 lib/xliff/parser.rb