30 votes

Ruby : comment ajouter "# encoding : UTF-8" automatiquement ?

Existe-t-il une gemme qui ajoute # encoding: UTF-8 à chaque fichier Ruby automatiquement ?

Ou existe-t-il un autre moyen d'éviter que le invalid multibyte char (US-ASCII) dans l'ensemble du projet Ruby on Rails (et non dans une seule classe) ?

28voto

Paul McMahon Points 791

Mise à niveau vers Ruby 2.0 car il fait d'UTF-8 l'encodage par défaut, supprimant ainsi le besoin de commentaires magiques.

24voto

Mirko Points 2719

Essayez codage magique gem, il peut insérer un commentaire magique uft-8 dans tous les fichiers ruby de votre application.

[EDIT] Après être passé à SublimeText, j'utilise maintenant auto-encodage pour ruby plugin.

6voto

Benoit Points 35553

Vim :

:args **/*.ruby
:set hidden
:argdo norm! O# encoding: UTF-8
:wqa

2voto

Si vous utilisez Sublime Text 2, vous pouvez utiliser un plugin qui inclut automatiquement la déclaration d'encodage lorsque cela est nécessaire : https://github.com/elomarns/auto-encoding-for-ruby .

2voto

Pourquoi ne pas simplement exécuter un script ?

#!/usr/bin/env ruby1.9.1
require 'find'

fixfile = []

Find.find('.') do |path|
  next unless /\.rb$/.match(path);
  File.open(path) do |file|
    count = 0;
    type = :lib
    file.each do |line|
      if count == 0 and /#!/.match(line)
        type = :script
      end
      if  /utf/.match(line)
        break
      end
      if (count += 1) > 10 then
        fixfile.push path:path, type:type
        break
      end
    end
    if file.eof?
        fixfile.push path:path, type:type
    end
  end
end

fixfile.each do |info|
  path = info[:path]
  backuppath = path + '~'
  type = info[:type]
  begin
     File.delete(backuppath) if File.exist?(backuppath)
     File.link(path, backuppath)
  rescue Errno::ENOENT => x
     puts "could not make backup file '#{backuppath}' for '#{ path }': #{$!}"
     raise
  end
  begin
    inputfile = File.open(backuppath, 'r')
    File.unlink(path)
    File.open(path, 'w') do |outputfile|
      if type == :script
        line = inputfile.readline
        outputfile.write line
      end
      outputfile.write "# encoding: utf-8\n"
      inputfile.each do |line|
        outputfile.write line
      end
      inputfile.close
      outputfile.close
    end
  rescue => x
    puts "error: #{x} #{$!}"
    exit
  end

Pour le rendre automatique, ajoutez ceci à votre Rakefile.

Tu pourrais courir file -bi #{path} et chercher encodage=utf-8 si vous voulez seulement mettre à jour les fichiers qui ont des caractères utf-8.

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X