Module: Localization

Included in:
ApplicationController, ApplicationHelper, LString
Defined in:
lib/localization.rb

Defined Under Namespace

Classes: LString

Constant Summary collapse

LOCALIZED_STRINGS =
{}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.load_localized_stringsObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/localization.rb', line 43

def self.load_localized_strings
  # Load language files
  Dir[RAILS_ROOT + '/lang/*.yaml'].each do |filename|
    filename =~ /(([a-z]+_?)+)\.yaml$/
    hash = YAML::load(File.read(filename))
    file_charset = hash['file_charset'] || 'ascii'
    lang = $1

    # convert string keys to symbols
    symbol_hash = Hash.new
    Iconv.open(CONFIG[:web_charset], file_charset) do |i|
      hash.each do |key, value|
        symbol_hash[key.to_sym] = i.iconv(value)
        if key =~ /^active_record_errors_(.*)/
          ActiveRecord::Errors.default_error_messages[$1.to_sym] =
            symbol_hash[key.to_sym]
        end
      end
    end

    LOCALIZED_STRINGS[lang] = symbol_hash
  end
end

Instance Method Details

#l(symbol, *arguments) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/localization.rb', line 7

def l(symbol, *arguments)
  language = CONFIG[:default_language]

  symbol = symbol.to_sym if symbol.is_a? String

  # translation of an LString is simply a call to to_s
  return symbol.to_s if symbol.is_a? LString

  # translation of an array
  if symbol.is_a? Array 
    raise ArgumentError.new("Cannot translate an empty array") if symbol.empty?
    raise ArgumentError.new("Symbol is an array, arguments must be empty") unless arguments.empty?
    arguments = symbol
    symbol = arguments.shift
  end

  begin
    translation = (LOCALIZED_STRINGS[language][symbol] or
                     LOCALIZED_STRINGS['en'][symbol] or
                     symbol.to_s)
  rescue
    translation = symbol.to_s
  end

  begin
    return translation % arguments
  rescue => e
    raise ArgumentError.new("Translation value #{translation.inspect} " + 
        "with arguments #{arguments.inspect} caused error '#{e.message}'")
  end
end

#valid_language?(language) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/localization.rb', line 39

def valid_language?(language)
  LOCALIZED_STRINGS.has_key? language
end