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

Options : 1 : Encoding 2 : Path TODO : check that the encoding specified is a valid encoding



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
# File 'lib/magic_encoding.rb', line 11

def self.process(options)
  
  # defaults
  encoding  = options[0] || "utf-8"
  directory = options[1] || Dir.pwd
  
  prefix = "# -*- encoding : #{encoding} -*-\n"
  
  # TODO : add options for recursivity (and application of the script to a single file)
  rbfiles = File.join(directory ,"**", "*.rb")
  Dir.glob(rbfiles).each do |filename|
    file = File.new(filename, "r+")
    
    lines = file.readlines
    
    # remove current encoding comment(s)
    while lines[0] && (
          lines[0].starts_with?("# encoding") || 
          lines[0].starts_with?("# coding") ||
          lines[0].starts_with?("# -*- encoding"))
      lines.shift
    end

    # set current encoding
    lines.insert(0,prefix)
    
    file.pos = 0
    file.puts(lines.join) 
    file.close
  end
  p "Magic comments set for #{Dir.glob(rbfiles).count} source files"
end