@@ -43,33 +43,33 @@ def translation
43
43
return puts 'FAIL: target_lang not supported' unless supported_languages . include? ( @target_lang . to_sym )
44
44
return puts 'FAIL: source_lang not supported' unless supported_languages . include? ( @source_lang . to_sym )
45
45
46
- {
47
- success : true ,
48
- translations : [ 'Ich bin foo bar' , 'Meine Name is foo bar' , 'Ich heise foo bar' ]
49
- }
50
-
51
- # response = Faraday.post(url) do |req|
52
- # req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
53
- # req.headers['Authorization'] = "DeepL-Auth-Key #{api_key}"
54
- # req.body = URI.encode_www_form(data)
55
- # end
46
+ response = Faraday . post ( url ) do |req |
47
+ req . headers [ 'Content-Type' ] = 'application/x-www-form-urlencoded'
48
+ req . headers [ 'Authorization' ] = "DeepL-Auth-Key #{ api_key } "
49
+ req . body = URI . encode_www_form ( data )
50
+ end
56
51
57
- # return puts 'FAIL: request failed' unless response.status == 200
52
+ return puts 'FAIL: request failed' unless response . status == 200
58
53
59
- # body = JSON.parse(response.body)
54
+ body = JSON . parse ( response . body )
60
55
61
- # return puts 'FAIL: no translations key' unless body.key?('translations')
56
+ # The response body will look something like:
57
+ # {"translations"=>[{"detected_source_language"=>"EN", "text"=>"Sie sind schwul"}]}
58
+ # Note how the translations key is an array which may return multiple translations.
62
59
63
- # translations = body[ 'translations']
60
+ return puts 'FAIL: no translations key' unless body . key? ( 'translations' )
64
61
65
- # return puts 'FAIL: no translations' if translations.empty?
62
+ translations = body [ ' translations'] . map { | t | t [ 'text' ] }
66
63
67
- # translation = translations.first['text']
64
+ # Here we map all suggested translations to a flat array like:
65
+ # ['Sie sind schwul', 'Suggestion 2']
68
66
69
- # puts "translations: #{translation}"
70
- # puts '---'
67
+ puts "translations: #{ translations } "
71
68
72
- # translation
69
+ {
70
+ success : true ,
71
+ translations : translations
72
+ }
73
73
end
74
74
75
75
def url
@@ -80,7 +80,8 @@ def data
80
80
{
81
81
text : @phrase ,
82
82
target_lang : @target_lang ,
83
- source_lang : @source_lang
83
+ source_lang : @source_lang ,
84
+ formality : 'prefer_more'
84
85
}
85
86
end
86
87
0 commit comments