Rails Faker 如何自定义本地语言文件?或者覆盖原来的语言文件

zhaopei · October 28, 2015 · Last by dc2000 replied at November 02, 2015 · 3152 hits

github 的文档中这样写:

Customization

Since you may want to make addresses and other types of data look different depending on where in the world you are (US postal codes vs. UK postal codes, for example), Faker uses the I18n gem to store strings (like state names) and formats (US postal codes are NNNNN while UK postal codes are AAN NAA), allowing you to get different formats by switching locales. Just set Faker::Config.locale to the locale you want, and Faker will take care of the rest.

If your locale doesn't already exist, create it in the \lib\locales\ directory and you can then override or add elements to suit

en-au-ocker: faker: name: # Existing faker field, new data first_name: [Charlotte, Ava, Chloe, Emily] # New faker fields ocker_first_name: [Bazza, Bluey, Davo, Johno, Shano, Shazza] region: [South East Queensland, Wide Bay Burnett, Margaret River, Port Pirie, Gippsland, Elizabeth, Barossa]

我在本地的 config/environments/test.rb 中加入了 Faker::Config.locale = 'zh-HK' 然后创建 lib/locales/zh-HK.yml 文件 zh-HK.yml 文件如下图 执行 rails console test 后

显示是 zh-HK,但是生成的 name 是英文的,不知道什么原因?

控制台程序和你的 Rail 的应用是有区别的,控制台程序只会去找 Rails 框架中的和中文相关的“zh-CN.yml”和“zh-TW.yml”两个文件,所以你自己写的文件名,Faker 在控制台是找不到的,因为他是读的“I18n”的配置文件。你给他指定的 locales 的话 Faker::Config.locale='zh-HK' ,由于控制台中它只能找到“zh-CN.yml”和“zh-TW.yml”文件,所以找不到指定文件的话就会读取默认配置,获取一个英文的随机名字。命令行的话,你像下面这么做,设置适当的解码格式应该就对了:

如果你要配置自己的 yml 文件的话,比如“zh-HK.yml”,你得把这个名为“zh-HK.yml”的文件放在“Your App/config/locales”下面,并在test.rb给你的yml文件做配置。

#1 楼 @dc2000 If your locale doesn't already exist, create it in the \lib\locales\ directory and you can then override or add elements to suit 文档上说要放在\lib\locales 下面, 我一会放在 config/locales 下面试试

#1 楼 @dc2000 faker 中文支持不太好,自定义的放在 config/locales 下面也不管用,

不管用总会报错吧,报什么错误,和什么相关的。然后去一步一步定位一下,你这样和没说一样。

中单大魔王 Faker

昨天又看了一下书,发现 yaml 文件的语法和一般的程序不一样。具体可以参考这里。http://www.yaml.org/spec/1.2/spec.html。它里面有这么一段话 “YAML’s block collections use indentation for scope and begin each entry on its own line. Block sequences indicate each entry with a dash and space ( “- ”). Mappings use a colon and space (“: ”) to mark each key: value pair. Comments begin with an octothorpe (also called a“hash”, “sharp”, “pound”, or“number sign” - “#”). " 意思就是属性声明的时候必须使用 (“: ”) 就是一个冒号加一个空格来匹配。 ”To maintain portability, tab characters must not be used in indentation,“ 在 yaml 文件中也就是说禁止用 Tab 键。

你可以检查一下,你的 yaml 文件中是否使用了 tab 或者少了空格。如果不按他的要求做,rails 会解析不了 yaml 文件。具体的内容你可以参考上面的文档说明。

You need to Sign in before reply, if you don't have an account, please Sign up first.