Module: Multilang

Defined in:
lib/multilang.rb,
lib/multilang/slot.rb,
lib/multilang/version.rb,
lib/multilang/language_names.rb

Defined Under Namespace

Modules: LanguageNames Classes: Slot

Constant Summary collapse

SLOT_KEY =
:@__multilang_slot__
VERSION =
'0.0.1'

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



50
51
52
# File 'lib/multilang.rb', line 50

def self.included(klass)
  register klass
end

.register(mod, options = {}) { ... } ⇒ Object

Support the class or the module to multilingualization.

Parameters:

  • mod (Class, Module)

    the class (or the module) to register

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :as (String)

    the language name

  • :as (Symbol)

    the language code (ISO639-2 or ISO639-1)

  • :with (String)

    the path of the file to dependent

Yields:

  • call once at getting the class (or the module) first

Raises:

  • (TypeError)

See Also:



17
18
19
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/multilang.rb', line 17

def self.register(mod, options = {}, &first)
  type = mod.class.name.downcase
  raise TypeError, "can't convert #{mod.class} into #{Module}" unless mod.is_a?(Module)
  raise ArgumentError, "anonymous #{type} can't register" if mod.name.nil?

  namespace = mod.name.split('::')
  class_name = namespace.pop
  language_spec = options[:as] || class_name

  if options[:with]
    path = options[:with]

    first = if block_given?
              f = first
              lambda { require path; f.call }
            else
              lambda { require path }
            end
  end

  raise ArgumentError, "can't permit top-level #{type}" if namespace.empty?
  parent = namespace.inject(Object) { |parent, name| parent.const_get(name) }

  slot = if parent.instance_variable_defined?(SLOT_KEY)
           parent.instance_variable_get(SLOT_KEY)
         else
           parent.extend(Slot::Access)
           parent.instance_variable_set(SLOT_KEY, Slot.new)
         end

  slot.register(language_spec, mod, &first)
end