]> git.openstreetmap.org Git - rails.git/blob - vendor/plugins/i18n_data/lib/i18n_data/file_data_provider.rb
7aec752a11c60e3d369c49f60e3f6e178b10f364
[rails.git] / vendor / plugins / i18n_data / lib / i18n_data / file_data_provider.rb
1 module I18nData
2   module FileDataProvider
3     DATA_SEPERATOR = ";;"
4     extend self
5
6     def codes(type,language_code)
7       unless data = read_from_file(type,language_code)
8         raise NoTranslationAvailable.new("#{type}-#{language_code}")
9       end
10       data
11     end
12
13     def write_cache(provider)
14       languages = provider.codes(:languages,'EN').keys
15       languages.each{|language_code|
16         [:languages,:countries].each {|type|
17           begin
18             data = provider.send(:codes,type,language_code)
19             write_to_file(data,type,language_code)
20           rescue NoTranslationAvailable
21           end
22         }
23       }
24     end
25
26   private
27
28     def read_from_file(type,language_code)
29       file = cache_for(type,language_code)
30       return nil unless File.exist?(file)
31       data = {}
32       IO.read(file).split("\n").each{|line|
33         code, translation = line.split(DATA_SEPERATOR)
34         data[code] = translation
35       }
36       data
37     end
38
39     def write_to_file(data,type,language_code)
40       return if data.empty?
41       file = cache_for(type,language_code)
42       FileUtils.mkdir_p(File.dirname(file))
43       File.open(file,'w') do |f|
44         f.puts data.map{|code,translation|"#{code}#{DATA_SEPERATOR}#{translation}"} * "\n"
45       end
46     end
47
48     def cache_for(type,language_code)
49       cache("#{type}-#{language_code}")
50     end
51
52     def cache(file)
53       File.join(File.dirname(__FILE__),'..','..','cache','file_data_provider',"#{file}.txt")
54     end
55   end
56 end