开发者

Rails global Encoding configuration?

开发者 https://www.devze.com 2023-03-25 08:53 出处:网络
I\'m working on a Rails project that has strings with spanish characters: ñ, á, é, í, ó, ú, etc.

I'm working on a Rails project that has strings with spanish characters: ñ, á, é, í, ó, ú, etc.

I have to use the "coding" comment (# coding: utf-8) at the top of every single file that has these characters to avoid errors when running the application.

How could I set this option globally instead of typing this comment in开发者_如何学Python each file? I guess it should go in the initializers or environment files.


There's an excellent blog post by James Edward Gray on this topic.

You shouldn't set this globally : your source files may be utf-8 encoded, but the author of some gem you're using might have used Shift JIS or something else. This will end with a big bang.

An intermediate solution would be using a rake task to check for the presence of the magic comment and adding it if not present (code shamelessly stolen from this blog post) :

desc "Manage the encoding header of Ruby files"
task :check_encoding_headers => :environment do
  files = Array.new
  ["*.rb", "*.rake"].each do |extension|
    files.concat(Dir[ File.join(Dir.getwd.split(/\\/), "**", extension) ])
  end

  files.each do |file|
    content = File.read(file)
    next if content[0..16] == "# coding: utf-8\n\n"

    ["\n\n", "\n"].each do |file_end|
      content = content.gsub(/(# encoding: utf-8#{file_end})|(# coding: utf-8#{file_end})|(# -*- coding: utf-8 -*-#{file_end})/i, "")
    end

    new_file = File.open(file, "w")
    new_file.write("# coding: utf-8\n\n"+content)
    new_file.close
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消