You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
764 B

  1. # frozen_string_literal: true
  2. class LanguageDetector
  3. attr_reader :text, :account
  4. def initialize(text, account = nil)
  5. @text = text
  6. @account = account
  7. end
  8. def to_iso_s
  9. detected_language_code || default_locale.to_sym
  10. end
  11. private
  12. def detected_language_code
  13. detected_language[:code].to_sym if detected_language_reliable?
  14. end
  15. def detected_language
  16. @_detected_language ||= CLD.detect_language(text_without_urls)
  17. end
  18. def detected_language_reliable?
  19. detected_language[:reliable]
  20. end
  21. def text_without_urls
  22. text.dup.tap do |new_text|
  23. URI.extract(new_text).each do |url|
  24. new_text.gsub!(url, '')
  25. end
  26. end
  27. end
  28. def default_locale
  29. account&.user&.locale || I18n.default_locale
  30. end
  31. end