Module: AddMagicComment

Defined in:
lib/magic_encoding.rb

Overview

A simple library to prepend magic comments for encoding to multiple “.rb” files

Class Method Summary collapse

Class Method Details

.process(options) ⇒ Object

TODO : allow use of only one option, so the encoding would be guessed (maybe using ‘file –mime`?)



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/magic_encoding.rb', line 12

def self.process(options)

  # defaults
  encoding  = options[0] || "utf-8"
  directory = options[1] || Dir.pwd

  #prefix = "-*- encoding : #{encoding} -*-\n"
  prefix = "encoding: utf-8\n"

  # TODO : add options for recursivity (and application of the script to a single file)

extensions = {
	'rb' => '# {text}',
	'rake' => '# {text}',
	'haml' => '-# {text}',
}

count = 0
extensions.each do |ext, comment_style|
	rbfiles = File.join(directory ,'**', '*.'+ext)
	Dir.glob(rbfiles).each do |filename|
		file = File.new(filename, "r+")

		lines = file.readlines

		# remove current encoding comment(s)
      while lines[0].match(/^-?# ?(-\*-)? ?(en)?coding/)
        lines.shift
      end

		# set current encoding
		lines.insert(0,comment_style.sub('{text}', prefix))
		count += 1

		file.pos = 0
		file.puts(lines.join)
		file.close
	end
end

  puts "Magic comments set for #{count} source files"
end