lib/google_translate_tts.rb in google-translate-tts-0.1.0 vs lib/google_translate_tts.rb in google-translate-tts-0.2.0
- old
+ new
@@ -1,50 +1,50 @@
# frozen_string_literal: true
-require "cgi"
require "faraday"
-require "fileutils"
-require "securerandom"
-require "tempfile"
require_relative "google_translate_tts/constanting"
require_relative "google_translate_tts/fileable"
+require_relative "google_translate_tts/utils"
require_relative "google_translate_tts/version"
module GoogleTranslateTts
include Constanting
include Fileable
+ include Utils
class << self
def fetch(phrase, **options)
with_temp_file do |file|
- lang = options.fetch(:lang, "en_US")
- filename = options.fetch(:file, "file")
+ lang, filename = options.values_at(:lang, :file)
+ filename ||= options.fetch(:file, "file")
- response = Faraday.get(tts_resource_url(q: phrase, tl: lang))
+ response = Faraday.get(translate_tts_url(q: phrase, tl: lang))
file.write(response.body)
- FileUtils.cp(file.path, "#{filename}.mp3")
+ copy_file(file.path, "#{filename}.mp3")
end
end
private
- def tts_resource_url(**params)
+ def translate_tts_url(**params)
"#{self::BASE_URL}/translate_tts?#{build_params(**params)}"
end
- def build_params(**kwargs)
- kwargs[:tl] ||= 'en'
+ def default_params
+ { ie: "UTF-8", client: "tw-ob", q: "", tl: "en_US" }
+ end
- params = {
- ie: 'UTF-8',
- client: 'tw-ob',
- q: "",
- }.merge(**kwargs)
+ def build_params(**custom_params)
+ custom_params[:tl] ||= "en"
+ params_encode(default_params.merge(**custom_params))
+ end
- # params.map { |(key, value)| pp [key, value] }
- params.map { |(key, value)| "#{key}=#{CGI.escape(value)}" }.join("&")
+ def params_encode(params)
+ params
+ .map { |(key, value)| "#{key}=#{url_encode(value)}" }
+ .join("&")
end
end
end