Module: Europeana::API::Record::LangMap

Defined in:
lib/europeana/api/record/lang_map.rb

Overview

Methods for working with “LangMap” data types in Record API JSON responses

Constant Summary collapse

DEPRECATED_ISO_LANG_CODES =
%w(in iw jaw ji jw mo mol scc scr sh)
NON_ISO_LANG_CODES =

Special keys API may return in a LangMap, not ISO codes TODO: Empty key acceptance is a workaround for malformed API data

output; remove when fixed at source
['def', '']

Class Method Summary collapse

Class Method Details

.known_lang_map_key?(key) ⇒ Boolean

Is the argument a known language map key?

Parameters:

  • key (String)

    String to check

Returns:

  • (Boolean)


39
40
41
42
43
44
# File 'lib/europeana/api/record/lang_map.rb', line 39

def known_lang_map_key?(key)
  key = key.dup.downcase
  DEPRECATED_ISO_LANG_CODES.include?(key) ||
    NON_ISO_LANG_CODES.include?(key) ||
    !ISO_639.find(key.split('-').first).nil?
end

.lang_map?(candidate) ⇒ Boolean

Is the argument a language map?

Critera:

  • Must be a Hash.

  • Must have only keys which are known language codes

Parameters:

  • candidate (Object)

    Object to check

Returns:

  • (Boolean)


30
31
32
33
# File 'lib/europeana/api/record/lang_map.rb', line 30

def lang_map?(candidate)
  return false unless candidate.is_a?(Hash)
  candidate.keys.map(&:to_s).all? { |key| known_lang_map_key?(key) }
end

.lang_map_value(lang_map, locale) ⇒ Array<Object>?

Fetch the language map value for a given locale

Parameters:

  • lang_map (Hash)

    Verified language map

  • locale (String)

    Locale to fetch the value for

Returns:

  • (Array<Object>, nil)

    Array of value(s) for the given locale, or nil if none are present



78
79
80
81
82
# File 'lib/europeana/api/record/lang_map.rb', line 78

def lang_map_value(lang_map, locale)
  keys = salient_lang_map_keys(lang_map, locale)
  return nil unless keys.present?
  keys.map { |k| lang_map[k] }.flatten.uniq
end

.localise_lang_map(lang_map) ⇒ Object+

Localise a language map

  1. If the argument is not a language map, return as-is

  2. If the language map has a key for the current locale, return that value

  3. If the language map has a key for the default locale, return that value

  4. Else, return all values

Arrays will be recursed over, localising each element.

Parameters:

  • lang_map (Object)

    Object to attempt to localise

Returns:

  • (Object, Array<Object>)

    Localised value



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/europeana/api/record/lang_map.rb', line 59

def localise_lang_map(lang_map)
  if lang_map.is_a?(Array)
    return lang_map.map { |val| localise_lang_map(val) }
  end

  return lang_map unless lang_map?(lang_map)

  lang_map_value(lang_map, ::I18n.locale.to_s) ||
    lang_map_value(lang_map, ::I18n.default_locale.to_s) ||
    lang_map_value(lang_map, 'def') ||
    lang_map.values
end