Skip to content

Instantly share code, notes, and snippets.

@kch
Created September 27, 2010 20:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kch/599760 to your computer and use it in GitHub Desktop.
Save kch/599760 to your computer and use it in GitHub Desktop.
Add the encoding magic comment to the ruby files passed as arguments
#!/usr/bin/env ruby
# encoding: UTF-8
ARGV.reject! { |path| !File.file?(path) }
(puts DATA.read.gsub("$0", File.basename($0)); exit 1) if ARGV.empty?
ARGV.each do |path|
ls = IO.readlines(path)
ix = ls[0] !~ /^#!/ ? 0 : 1
next if ls[ix] =~ /#.*?coding\s*[:=]\s*\S/
ls.insert ix, "# encoding: UTF-8\n", ("\n" unless ls[ix] =~ /^#?\s*\n/)
open(path, 'w') { |f| f.write ls.join }
end
__END__
Add the unicode magic comment to ruby files.
* Files are modified in-place.
* If a file already contains a magic comment, it's skipped.
* Comment is added below the shebang if it exists, otherwise as the first line.
Usage:
$0 file-1 [file-2 ... file-n]
Examples:
# Add comment to standalone ruby files:
$0 foo.rb bar.rb
# Add comment to an entire ruby library or app:
find . -name '*.rb' -type f -print0 | xargs -0 $0
# Add comment to app files in a rails application:
find app config lib -name '*.rb' -type f -print0 | xargs -0 $0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment