Sha256: c92b43ac5f1ad9cfb4d730b4de0ec8d5297ea5f379aaea7383e3a4f81854f259

Contents?: true

Size: 1.52 KB

Versions: 4

Compression:

Stored size: 1.52 KB

Contents

module DeepL
  module Requests
    class Translate < Base
      BOOLEAN_CONVERSION = { true => '1', false => '0' }.freeze
      ARRAY_CONVERSION = ->(value) { value.is_a?(Array) ? value.join(', ') : value }.freeze
      OPTIONS_CONVERSIONS = {
        split_sentences: BOOLEAN_CONVERSION,
        preserve_formatting: BOOLEAN_CONVERSION,
        non_splitting_tags: ARRAY_CONVERSION,
        ignore_tags: ARRAY_CONVERSION
      }.freeze

      attr_reader :text, :source_lang, :target_lang, :ignore_tags, :non_splitting_tags

      def initialize(api, text, source_lang, target_lang, options = {})
        super(api, options)
        @text = text
        @source_lang = source_lang
        @target_lang = target_lang

        tweak_parameters!
      end

      def request
        payload = { text: text, source_lang: source_lang, target_lang: target_lang }
        build_texts(*post(payload))
      end

      private

      def tweak_parameters!
        OPTIONS_CONVERSIONS.each do |param, converter|
          next unless option?(param) && converter[option(param)]
          set_option(param, converter[option(param)])
        end
      end

      def build_texts(request, response)
        data = JSON.parse(response.body)

        texts = data['translations'].map do |translation|
          Resources::Text.new(translation['text'], translation['detected_source_language'],
                              request, response)
        end

        texts.size == 1 ? texts.first : texts
      end

      def path
        'translate'
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
deepl-rb-2.2.2 lib/deepl/requests/translate.rb
deepl-rb-2.2.1 lib/deepl/requests/translate.rb
deepl-rb-2.2.0 lib/deepl/requests/translate.rb
deepl-rb-2.1.0 lib/deepl/requests/translate.rb