Class: JSPreprocessor

Inherits:
Object
  • Object
show all
Defined in:
lib/JSPreprocessor.rb

Instance Method Summary collapse

Constructor Details

#initializeJSPreprocessor

Returns a new instance of JSPreprocessor.



5
6
7
# File 'lib/JSPreprocessor.rb', line 5

def initialize
  @defines = []
end

Instance Method Details

#process(cwd, main_file) ⇒ Object



9
10
11
12
13
# File 'lib/JSPreprocessor.rb', line 9

def process(cwd, main_file)
  main = File.open(cwd + main_file).read.split "\n"
  compiled_file = recurse_files(cwd, main).join "\n"
  replace_defines compiled_file
end

#recurse_files(cwd, file) ⇒ Object



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
54
55
# File 'lib/JSPreprocessor.rb', line 15

def recurse_files(cwd, file)
  file.each_with_index do |line, index|
    if line.include? '#include'
      if line.include? '<' #inclusion guards, use bower
        if File.file? '.bowerrc' # check if they keep the bower files somewhere else
          bowerrc = JSON.parse File.open('.bowerrc').read
          if !bowerrc['directory'].nil? # if a custom directory has been set
            @bower_dir = bowerrc['directory']
          else
            @bower_dir = 'bower_components'
          end
        else
          @bower_dir = 'bower_components'
        end

        package = line.match(/<(.*)>/)[1]
        package_json = "#{@bower_dir}/#{package}/bower.json"
        package_path = JSON.parse(File.open(package_json).read)['main']

        if package_path.class == Array
          package_path.each_with_index do |package, index|
            if package[-2..-1] == 'js'
              package_path = package
              break
            end
          end
        end

        library = File.open("#{@bower_dir}/#{package}/#{package_path}").read
        file[index] = library
      else
        to_include = cwd + line[10..-2] + '.js'
        next_wd = Pathname.new(to_include).dirname.to_s + '/'
        file[index] = recurse_files next_wd, File.open(to_include).read.split("\n")
      end
    elsif line.include? '#define'
      @defines << line[8..-1].split(' ')
      file.delete_at index
    end
  end
end

#replace_defines(file) ⇒ Object



57
58
59
60
61
62
63
# File 'lib/JSPreprocessor.rb', line 57

def replace_defines(file)
  @defines.each do |definition|
    file.gsub! definition[0], definition[1]
  end

  file
end