Module: StripMagicComment

Defined in:
lib/encoding_magic.rb

Overview

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

Class Method Summary collapse

Class Method Details

.process(options) ⇒ Object

Options : 1 : Encoding 2 : Path



8
9
10
11
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
# File 'lib/encoding_magic.rb', line 8

def self.process(options)

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

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


  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.to_a
      striped = 0
      # remove current encoding comment(s)
      while lines[0].respond_to?(:match) && lines[0].match(/#{encoding}/)
        lines.shift
        striped += 1
      end

      if striped > 0
        count += 1
      end

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

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