Class: Ramaze::Helper::Localize::Dictionary

Inherits:
Object
  • Object
show all
Defined in:
lib/ramaze/helper/localize.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDictionary

Returns a new instance of Dictionary.



33
34
35
# File 'lib/ramaze/helper/localize.rb', line 33

def initialize
  @dict = {}
end

Instance Attribute Details

#dictObject (readonly)

Returns the value of attribute dict.



31
32
33
# File 'lib/ramaze/helper/localize.rb', line 31

def dict
  @dict
end

Instance Method Details

#[](locale) ⇒ Object



68
69
70
# File 'lib/ramaze/helper/localize.rb', line 68

def [](locale)
  @dict[arg_to_locale(locale)]
end

#[]=(locale, dict) ⇒ Object



72
73
74
# File 'lib/ramaze/helper/localize.rb', line 72

def []=(locale, dict)
  @dict[arg_to_locale(locale)] = dict
end

#load(locale, options = {}) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/ramaze/helper/localize.rb', line 76

def load(locale, options = {})
  if file = options.delete(:yaml)
    dict = ::YAML.load_file(file)
  elsif hash = options.delete(:hash)
    dict = hash
  elsif marshal = options.delete(:marshal)
    dict = Marshal.load(File.read(marshal))
  else
    raise ArgumentError, "either :yaml, :marshal, or :hash"
  end

  @dict[arg_to_locale(locale)] = dict
end

#localesObject



64
65
66
# File 'lib/ramaze/helper/localize.rb', line 64

def locales
  @dict.keys
end

#lookup(string, locales) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/ramaze/helper/localize.rb', line 54

def lookup(string, locales)
  locales.each do |locale|
    next unless dict = self[locale]
    next unless translated = dict[string]
    return translated
  end

  string
end

#translate(string, locales, substitute) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ramaze/helper/localize.rb', line 37

def translate(string, locales, substitute)
  target = string.to_s.dup
  locales = locales.flatten.uniq

  if substitute
    substitute.each do |key, value|
      target.gsub!(/\{#{Regexp.escape(key)}\}/, lookup(value, locales))
    end
    return target
  elsif target =~ /\{/
    target.gsub!(/\{([^\}]+)\}/){ lookup($1, locales) }
    return target
  else
    lookup(target, locales)
  end
end