Class: Join::Compiler

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

Overview

Takes multiple files and compiles them into a single file

Constant Summary collapse

F_TYPES =
{
  :javascript => '.js',
  :css => '.css'
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Compiler

Returns a new instance of Compiler.



8
9
10
11
12
# File 'lib/join/compiler.rb', line 8

def initialize(opts = {})
  @dest = opts[:dest] || 'compressed.js'
  @compressed = opts[:compressed] || false
  @compressor = Join::Compressor.new
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



6
7
8
# File 'lib/join/compiler.rb', line 6

def options
  @options
end

Instance Method Details

#append_to(filename, data) ⇒ Object

Open a file and append data to the file.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/join/compiler.rb', line 31

def append_to(filename, data)
  begin
    File.open(filename, 'a') do |f|
      if @compressed == true
        ext = get_ext(filename)
        type = get_file_type(ext)
        data = @compressor.compress(type, data) 
      end
      f.puts data
    end
    show_success_message
  rescue
    STDOUT.puts "Cannot append to file"
    exit #Terminate if file can't be found
  end    
end

#flush!(file) ⇒ Object

Delete or flush the contents of a given file.



20
21
22
# File 'lib/join/compiler.rb', line 20

def flush!(file)
  File.open(file, 'w').truncate(0)
end

#get_ext(path) ⇒ Object



48
49
50
# File 'lib/join/compiler.rb', line 48

def get_ext(path)
  File.extname(path)
end

#get_file_type(ext) ⇒ Object

We need this to determine what type of file we are dealing with before sending the data to the file compressor



26
27
28
# File 'lib/join/compiler.rb', line 26

def get_file_type(ext)
  F_TYPES.key(ext)
end

#join(args) ⇒ Object

When given an array of files, (e.g [file1.js, file2.js]) join them together and output the result into the destination set in @options



66
67
68
69
70
# File 'lib/join/compiler.rb', line 66

def join(args)
  flush!(@dest) if File.exists? @dest #Empty file if it already exists
  result = args.map { |p| read_file(p) }.join("\n")
  append_to(@dest, result)
end

#read_file(path) ⇒ Object



56
57
58
59
60
61
# File 'lib/join/compiler.rb', line 56

def read_file(path)
  raise "File does not exist" unless File.exists?(path)
  File.open(path, 'r') do |f|
    f.read
  end
end

#show_success_messageObject



52
53
54
# File 'lib/join/compiler.rb', line 52

def show_success_message
  STDOUT.puts "Successfully joined file for production"
end