Class: SlimKeyfy::Slimutils::TranslationKeyGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/slimkeyfy/slimutils/key_generator.rb

Constant Summary collapse

VALID =
/[^0-9a-z]/i
DEFAULT_KEY_NAME =
"default_key"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(translation) ⇒ TranslationKeyGenerator

instance methods



72
73
74
75
# File 'lib/slimkeyfy/slimutils/key_generator.rb', line 72

def initialize(translation)
  # keys must be in english!
  @translation = self.class.translate_key( translation )
end

Class Method Details

.translate_key(translation) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/slimkeyfy/slimutils/key_generator.rb', line 55

def self.translate_key(translation)
  if translator_options[:api] && translation && !translation.empty?
    begin
      # language can be detected automatically but this is noticeably slower than providing one.
      yt.translate( translation, from: translator_options[:from_locale], to: :en )
    rescue Exception => e
      p e.inspect
      return translation
    end
  elsif translator_options[:from_locale].to_s == 'ru'
    ::Russian.transliterate(translation)
  else
    translation
  end
end

.translator_optionsObject

class public methods



43
44
45
# File 'lib/slimkeyfy/slimutils/key_generator.rb', line 43

def self.translator_options
  @translator_options ||= {}
end

.translator_options=(new_options) ⇒ Object



47
48
49
# File 'lib/slimkeyfy/slimutils/key_generator.rb', line 47

def self.translator_options=( new_options  )
  @translator_options = new_options
end

.ytObject



51
52
53
# File 'lib/slimkeyfy/slimutils/key_generator.rb', line 51

def self.yt
  @yt ||= Yandex::Translator.new( translator_options[:api] )
end

Instance Method Details

#generate_key_nameObject



77
78
79
80
81
82
83
84
85
# File 'lib/slimkeyfy/slimutils/key_generator.rb', line 77

def generate_key_name
  normalized_translation = ""
  if not (@translation.nil? or @translation.empty?) then
    normalized_translation = @translation.gsub(VALID, "_").gsub(/[_]+/, "_").downcase
    normalized_translation = normalized_translation.split("_")[0..3].join("_")
  end
  return DEFAULT_KEY_NAME if is_not_valid?(normalized_translation.strip)
  strip_underscores(normalized_translation)
end

#is_not_valid?(normalized_translation) ⇒ Boolean

Returns:

  • (Boolean)


87
88
89
# File 'lib/slimkeyfy/slimutils/key_generator.rb', line 87

def is_not_valid?(normalized_translation)
  (normalized_translation.strip == "_" or normalized_translation.empty?)
end

#strip_underscores(s) ⇒ Object



91
92
93
94
95
96
97
98
99
# File 'lib/slimkeyfy/slimutils/key_generator.rb', line 91

def strip_underscores(s)
  if s.start_with?("_") then
    s = s[1..-1]
  end
  if s.end_with?("_") then
    s = s[0..-2]
  end
  s
end