字符数据是最为重要的数据类型,为什么呢 ? 因为程序是为人服务的,那些能直接读懂二进制数据的超人是很少的
要点:
如果你在Ruby中想使用不同的字符集,那么请记住
1. a: ASCII
2. n : NONE(ASCII)
3. e: EUC
4. s: SJIS
5. u: UTF-8
你可以这么设置,$KCODE = 'u' ,也可以这么设置,$KCODE = 'UTF-8' , 仅仅第一个字符(U)管用。
当使用utf-8的时候require jcode这个库会很有帮助。
消息目录是指用特定的语言表示的消息集合,是本地化思想中不可分割
想使用其基本功能,需要require 'gettext'
想使用更有用的实用程序,需要require 'gettext/utils'
Ruby1. 8 .6没有包含这个gettext库,需要自己安装 gem install gettext
关于gettext有三个关键的术语需要解释:
1. po - file : 可移植的对象文件,是人类可读的形式,每个po
2. mo - file :是可移植的二进制消息目录文件,是根据po-file创建的
3. text domain : 文本域,实际上是mo-file的basename
所以有了文本域,和应用程序绑定以后,我们只需要写一个po
网上找了个简单的例子:
require 'gettext'
class Person
include GetText
def initialize(name, age,children_num)
@name, @age, @children_num = name, age, children_num
blindtextdomain("myapp")
end
def show
puts _("information")
puts _("Name: %{name}, Age: %{age}") % {:name => @name, :age => @age}
puts n_("%{name} is an unmarried.", "%{name} has %{num} boy or girl firend.", @firend_num) % {:name => @name, :num => @firend_num }
end
end
alex = Person.new("Alex",26, 0 )
alex.show
mary = Person.new("Mary", 18, 0)
mary.show
上面的例子里,
puts _("Name: %{name}, Age: %{age}") % {:name => @name, :age => @age} ,这种写法我估计是gettext里实现的。
n_方法是除了单复数的。将上面的文件保存为myapp
require 'gettext/untils'
desc "Update pot/po file"
task :updatepo do
GetText.update_pofiles("myapp", ["person.rb"], "myapp 1.0.0")
end
desc "Create mo-files"
task :makemo do
GetText.create_mofiles
end
上面的代码中,update_pofiles将根据person
create_mofiles 将创建子目录data/locale/, 并根据po-file生成mo-file。
这样,当我们执行rake updatepo这个命令之后,将创建目录 myapp/po/myapp.pot. 打开myapp.pot这个文件会看到对应用程序的一些描述信息
#, fuzzy
这个表示是还没有被翻译的内容或者是需要校译的内容。
然后我们就可以复制myapp.pot这个文件为myapp
myapp/po/zh_ch/myapp.po目录下
myapp/
Rakefile
person.rb
po/
myapp.pot
zh_cn/myapp.po
de/myapp.po
.
.
data/
locale/
zh_cn/LC_MESSAGES/myapp.mo
de/LC_MESSAGES/myapp.mo
.
.
然后我们可以测试一下:
首先我们需要设置环境变量,
export GETTEXT_PATH="data/locale"
export LANG="zh_CN.UTF-8"
ruby person.rb
这样应用程序会根据变量LANG的设置情况输出对应的值。
以上设置环境变量主要是为了在控制台下测试这个简单程序而已