Module: HumanID::Transliteration

Defined in:
lib/humanid/transliteration.rb

Defined Under Namespace

Classes: Behaviour, MalformedHumanIDError

Class Method Summary collapse

Class Method Details

.behaviourObject



61
62
63
# File 'lib/humanid/transliteration.rb', line 61

def behaviour
  Behaviour.instance
end

.perform(str, options = {}) ⇒ Object

HumanID::Transliteration.perform(‘Well-known English writer’)

=> 'well-known-english-writer'

HumanID::Transliteration.perform(‘Well-known English writer’, normalize: false, downcase: false)

=> 'Well-known English writer'

HumanID::Transliteration.perform(‘Пушкин, Александр Сергеевич’)

=> 'pushkin-aleksandr-sergeevich'

HumanID::Transliteration.perform(‘Пушкин, Александр Сергеевич’, normalize: false, downcase: false)

=> 'Pushkin, Aleksandr Sergeevich'


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/humanid/transliteration.rb', line 20

def perform(str, options = {})
  previous_locale = I18n.locale
  I18n.locale     = I18n.default_locale
  separator       = options.fetch(:separator, behaviour.separator)
  downcase        = options.fetch(:downcase, behaviour.perform_downcase?)
  normalize       = options.fetch(:normalize, behaviour.perform_normalization?)

  str = str.join(separator) if str.is_a?(Array)
  str = I18n.transliterate(str)

  str = str.downcase if downcase

  if normalize

    # Replace non-word and non-ASCII characters with hyphens.
    str = str.gsub(/\W/, '-')

    # Strip leading and trailing hyphens.
    str = str.gsub(/(\A-+)|(-+\z)/, '')

    # Collapse hyphens.
    str = str.gsub(/-+/, '-')

  end

  str
ensure
  I18n.locale = previous_locale
end

.valid?(human_id) ⇒ Boolean

Returns:

  • (Boolean)


51
52
53
54
# File 'lib/humanid/transliteration.rb', line 51

def valid?(human_id)
  human_id = human_id.to_s if human_id.kind_of?(Symbol)
  human_id.kind_of?(String) && !!(human_id =~ behaviour.validation_regex)
end

.validate!(human_id) ⇒ Object



56
57
58
59
# File 'lib/humanid/transliteration.rb', line 56

def validate!(human_id)
  raise MalformedHumanIDError unless valid?(human_id)
  true
end