Class: Nagoro::Pipe::Localization

Inherits:
Object
  • Object
show all
Defined in:
lib/nagoro/pipe/localization.rb

Constant Summary collapse

CONFIG =
{
  :file => 'config/%s.yaml',
  :locales => %w[ en ],
  :default_language => 'en',
  :mapping => {'en-us' => 'en', 'ja' => 'jp'},
  :regex => /\[\[(.*?)\]\]/,
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLocalization

Returns a new instance of Localization.



23
24
25
# File 'lib/nagoro/pipe/localization.rb', line 23

def initialize
  load_dictionary
end

Instance Attribute Details

#dictObject

Returns the value of attribute dict.



9
10
11
# File 'lib/nagoro/pipe/localization.rb', line 9

def dict
  @dict
end

#localeObject

Returns the value of attribute locale.



9
10
11
# File 'lib/nagoro/pipe/localization.rb', line 9

def locale
  @locale
end

Class Method Details

.[](conf = {}) ⇒ Object



19
20
21
# File 'lib/nagoro/pipe/localization.rb', line 19

def self.[](conf = {})
  CONFIG.merge!(conf)
end

Instance Method Details

#call(template) ⇒ Object



40
41
42
43
44
45
# File 'lib/nagoro/pipe/localization.rb', line 40

def call(template)
  @template = template
  @template.gsub!(CONFIG[:regex]) do |e|
    localize($1)
  end
end

#load_dictionaryObject



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/nagoro/pipe/localization.rb', line 27

def load_dictionary
  file = CONFIG[:file]
  files = CONFIG[:locales].map{|l| [l, file % l]}
  existing, missing = files.partition{|(l,f)| File.file?(f)}
  FileUtils.mkdir_p(File.dirname(file)) unless missing.empty?
  missing.each{|(l,f)| FileUtils.touch(f)}

  @dict = {}
  files.each do |locale, file|
    @dict[locale] = YAML.load_file(file) || {}
  end
end

#localize(string) ⇒ Object



47
48
49
# File 'lib/nagoro/pipe/localization.rb', line 47

def localize(string)
  @dict[locale][string]
end

#resetObject



55
56
57
# File 'lib/nagoro/pipe/localization.rb', line 55

def reset
  @template = ''
end

#to_htmlObject



51
52
53
# File 'lib/nagoro/pipe/localization.rb', line 51

def to_html
  @template
end