Rails Rails 将某些页面静态化,在生成文件时遇到的错误

hz_qiuyuanxin · 2013年04月22日 · 最后由 hz_qiuyuanxin 回复于 2013年04月23日 · 3721 次阅读

需要是要将某些网页静态化,但是在写入文件时,发生一个这样的错误!百思不得其解! "\xE8" from ASCII-8BIT to UTF-8

在第一次写入时,由于所有文件都没有,故跑一次没有问题。可是再跑一次,问题就出现了,终端给出了上面说的那个编码的问题!

builds_static.rb

# encoding: utf-8
namespace :builds_static do

  desc "Generate all builds static pages and save them in /public/builds(rewrite if exist)"
  task generate: :environment do
    require 'rails/console/app'
    require 'rails/console/helpers'
    extend Rails::ConsoleMethods

    all_urls_and_paths = Build.all.each_with_object([]) do |build, array|
      array.concat urls_and_paths(build.id, build.app.code)
    end
    # remember add /builds/index.html
    all_urls_and_paths << builds_index_url_and_path
    generate_static_file(all_urls_and_paths)
  end

  private
  def builds_index_url_and_path
    ["/builds", "/builds/index.html"]
  end

  def urls_and_paths(build_id, code)
    [
      ["/builds/#{build_id}",         "/builds/#{build_id}.html"],
      ["/builds/#{build_id}.plist",   "/builds/#{build_id}.plist"],
      ["/apps/#{code}/builds/latest", "/builds/apps/#{code}.html"]
    ]
  end

  def generate_static_file(urls_paths)
    urls_paths.each do |url, path|
      r = app.get(url)
      if 200 == r
        File.open(Rails.public_path + path, "w+") { |f| f.write(app.response.body) }
      else
        $stderr.puts "Error generating static file #{path} #{r.inspect}"
      end
    end
  end

end

请问有没有人遇到过这种问题的?

File.open(Rails.public_path + path, "w+:ASCII-8BIT:utf-8") { |f| f.write(app.response.body) }

Or

File.open(Rails.public_path + path, "w+") do |f| 
  file.set_encoding("ASCII-8BIT:utf-8")
  f.write(app.response.body)
end

看看这样行不行

#1 楼 @ywjno

后来找到方法了:f.write(app.response.body.force_encoding("UTF-8")) 就可以了! 你说的那个方法我倒没试过

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