Rails Ruby on Rails 读写 yml 文件 (中文 utf-8 问题)

匿名 · 2013年08月05日 · 最后由 huberydu 回复于 2013年08月07日 · 6889 次阅读

写的一个 task,目的是把图片从服务器上迁移到七牛云上,然后读取数据时,把数据临时的保存在 yml 文件中,出现错误,如果是英文的话就没问题。 错误信息 Encoding::UndefinedConversionError: "\xE9" from ASCII-8BIT to UTF-8 from /home/xiaolong/.rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1/psych/visitors/emitter.rb:27:in write

自己到网上搜了下 http://runupwind.iteye.com/blog/1109238#comments

在 gemfile 中 增加 ya2yaml 我试了下,还是出错。

http://www.cnblogs.com/kting/archive/2011/09/15/2177530.html 修改 mysql2_adapter.rb 也没有用

代码如下

读取数据保存在 yml 文件中的相关代码

namespace :utils do
    desc "Deploy all picture in local to QiuNiuCloud"
    task :deploy_picture_to_qiniu => :environment do
        url = Rails.root.to_s+"/config/photos.yml"
        @tech = Technician.all
        self.save(@tech,url)
    end
end
def self.save(rules)  
    result = true  
    begin  
      File.open("#{url}", 'w') { |f|  
        YAML.dump(rules, f)  
      }  
  rescue => err  
     logger = Logger.new(Rails.root.to_s + '/log/err.log')  
     logger.error err  
     logger.close       
     result = false  
   end  
   result  
end

请问有遇到过类似问题的朋友没?

ruby 1.9.3 默认是不支持中文的,你在程序里指定一下 utf-8 编码这个问题就解决了。或者你用 Ruby2.0

之前也碰到过这个问题,读取 yml 的时候指定 ASCII-8BIT,File.open("xxxxxxx","r:ASCII-8BIT" ) 程序里再强制转 utf-8, str.force_encoding("UTF-8")

匿名 #3 2013年08月06日

#2 楼 @wym205 我是从数据库里读取数据后,往 yml 文件中写入的时候出现的问题

4 楼 已删除

看到一个别人的解决方法 YAML::ENGINE.yamler='syck' File.open("#{url}", 'w') { |f|
YAML.dump(rules, f)
}

匿名 #6 2013年08月07日

#5 楼 @wym205 谢拉,我换了种思路没有把它保存为 yml 文件了

需要 登录 后方可回复, 如果你还没有账号请 注册新账号