Class: OrdbokLib::Ordbok

Inherits:
Object
  • Object
show all
Defined in:
modules/ordbok.rb,
modules/lang_menu.rb

Overview

Note:

Period (.) is an illegal character in individual keys, as it is used as delimiter for nested keys.

Ordbok localization library for SketchUp extensions.

Examples:

# 'extension-dir/resources/en-US.lang'
# {"greeting":"Hello World!"}

# 'extension-dir/main.rb'
require "extension-dir/ordbok"
OB = Ordbok.new
OB[:greeting]
# => "Hello World!"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lang: nil, resource_dir: nil, remember_lang: true, pref_key: nil) ⇒ Ordbok

Initialize Ordbok object.

It is recommended to assign this object to constant for access throughout your extension.

Examples:

OB = Ordbok.new

Parameters:

  • lang (Symbol, nil) (defaults to: nil)

    The language to use. When nil, Ordbok fall backs to language from last session (if remember_lang is true and a value can be found), SketchUp’s language, en-US, or whatever language can be found.

  • resource_dir (String, nil) (defaults to: nil)

    Absolute path to directory containing language files. When nil, “resources” relative to where Ordbok.new is called is used.

  • remember_lang (Boolean) (defaults to: true)

    Save language preference betweens sessions.

  • pref_key (Symbol, nil) (defaults to: nil)

    Key to save language setting to. When nil, a key based on the Extension’s module is used.

Raises:

  • (LoadError)

    if no lang files exists in resource_dir.



44
45
46
47
48
49
50
51
52
# File 'modules/ordbok.rb', line 44

def initialize(lang: nil, resource_dir: nil, remember_lang: true, pref_key: nil)
  @caller_path  = caller_locations(1..1).first.path
  @resource_dir = resource_dir || default_resource_dir
  raise LoadError, "No .lang files found in #{@resource_dir}." if available_langs.empty?
  @remember_lang = remember_lang
  @pref_key      = pref_key || default_pref_key
  @lang_pref     = (lang && lang.to_sym) || (remember_lang && saved_lang) || nil
  load_language
end

Instance Attribute Details

#langSymbol

Returns the code of the currently used language.

Returns:

  • (Symbol)


57
58
59
# File 'modules/ordbok.rb', line 57

def lang
  @lang
end

#lang_prefSymbol (readonly)

Returns the code of the current lang preference. If no language has been explicitly chosen, nil is returned. Use lang to get the code of the actually used language.

Returns:

  • (Symbol)


64
65
66
# File 'modules/ordbok.rb', line 64

def lang_pref
  @lang_pref
end

#pref_keySymbol #pref_key=(value) ⇒ Object

Overloads:

  • #pref_keySymbol

    Get the key by witch the language preference is stored between sessions.

    Returns:

    • (Symbol)
  • #pref_key=(value) ⇒ Object

    Set the key by witch the language preference is stored between sessions.

    Parameters:

    • value (Symbol)


80
81
82
# File 'modules/ordbok.rb', line 80

def pref_key
  @pref_key
end

#remember_langBoolean #remember_lang=(value) ⇒ Object

Overloads:

  • #remember_langBoolean

    Get whether the chosen language should be restored in next session.

    Returns:

    • (Boolean)
  • #remember_lang=(value) ⇒ Object

    Set whether the chosen language should be restored in next session.

    Parameters:

    • value (Boolean)


72
73
74
# File 'modules/ordbok.rb', line 72

def remember_lang
  @remember_lang
end

Instance Method Details

#[](key, opts = {}) ⇒ String

Output localized string for key.

Formats string according to additional parameters, if any. If key is missing, warn and return stringified key.

Examples:

# (Assuming there is a resource directory with valid lang files)
OB = Ordbok.new

# (Assuming :greeting defined as "Hello World!")
OB[:greeting]
# => "Hello World!"

# Key can be String too.
OB["greeting"]
# => "Hello World!"

# (Assuming :interpolate defined as "Interpolate string here: %{string}.")
OB[:interpolate, string: "Hello World!"]
# => "Interpolate string here: Hello World!."

# Keys can be nested, defining groups of related messages.
# For nested nested keys, use String with period as delimiter.
# Note that "." is an illegal character within individual keys!
OB["message_notification.zero"]
# => "You have no new messages."

# The :count keyword is not only interpolated to the String, but also
# used to select nested entry (if available). This allows you to
# specify separate strings with different pluralization.

# If the count is 0, the entry :zero is used if available.
# (Assuming "message_notification.zero" is "You have no new message.")
OB["message_notification", count: 0 ]
# => "You have no new messages."

# If the count is 1, the entry :one is used if available.
# (Assuming "message_notification.one" is "You have %{count} new message.")
OB["message_notification", count: 1 ]
# => "You have 1 new message."

# Otherwise the entry :other is used.
# (Assuming "message_notification.other" is "You have %{count} new messages.")
OB["message_notification", count: 7 ]
# => "You have 7 new messages."

Parameters:

  • key (Symbol, String)
  • opts (Hash) (defaults to: {})

    Interpolation options. See Kernel.format for details.

Options Hash (opts):

  • :count (Numeric)

    The count keyword is not only interpolated to the string, but also used to select nested entry based on pluralization, if available (see example).

Returns:

  • (String)


182
183
184
185
186
187
188
189
190
191
# File 'modules/ordbok.rb', line 182

def [](key, opts = {})
  count = opts[:count]
  template = lookup(key, count)
  if template
    format(template, opts)
  else
    warn "key #{key} is missing."
    key.to_s
  end
end

#available_lang_namesHash{Symbol => String}

List names of available languages in the resources directory indexed by their code.

Returns:

  • (Hash{Symbol => String})


96
97
98
99
# File 'modules/ordbok.rb', line 96

def available_lang_names
  # No #to_h method in SU2014.
  Hash[available_langs.map { |l| [l, lang_name(l)] }]
end

#available_langsArray<Symbol>

List the available languages in the resources directory.

A language is a file with the extension .lang.

Returns:

  • (Array<Symbol>)


87
88
89
90
# File 'modules/ordbok.rb', line 87

def available_langs
  pattern = "#{@resource_dir.tr('\\', '/')}/*.lang"
  Dir.glob(pattern).map { |p| File.basename(p, ".*").to_sym }
end

#inspectObject



101
102
103
# File 'modules/ordbok.rb', line 101

def inspect
  "#<#{self.class.name}:#{object_id} (#{lang})>"
end

#lang_available?(lang) ⇒ Boolean

Check if a specific language is available.

Parameters:

  • lang (Symbol)

Returns:

  • (Boolean)


125
126
127
# File 'modules/ordbok.rb', line 125

def lang_available?(lang)
  File.exist?(lang_path(lang))
end

#lang_menu(menu, offer_system_lang: true, system_lang_name: "System Default") ⇒ Void

Create menu items for selecting language.

Examples:

OB = Ordbok.new(remember_lang: true)
menu = UI.menu("Plugins").add_submenu("My Extension").add_submenu("Language")
OB.lang_menu(menu)

Parameters:

  • menu (Sketchup::Menu)
  • offer_system_lang (Boolean) (defaults to: true)

    Whether to include “System Default” as an option for picking language based on SU language.

  • system_lang_name (String) (defaults to: "System Default")

    What to call menu item for system language. Note that this isn’t the name of any language itself but the phrase denoting no language is explicitly picked.

Returns:

  • (Void)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'modules/lang_menu.rb', line 24

def lang_menu(menu, offer_system_lang: true, system_lang_name: "System Default")
  if offer_system_lang
    item = menu.add_item(system_lang_name) { self.lang = nil }
    menu.set_validation_proc(item) { lang_pref.nil? ? MF_CHECKED : MF_UNCHECKED }
    menu.add_separator
  end

  available_lang_names.sort.each do |code, name|
    item = menu.add_item(name) { self.lang = code }
    if offer_system_lang
      menu.set_validation_proc(item) { lang_pref == code ? MF_CHECKED : MF_UNCHECKED }
    else
      menu.set_validation_proc(item) { self.lang == code ? MF_CHECKED : MF_UNCHECKED }
    end
  end

  nil
end