Class: Guard::EJS

Inherits:
Guard
  • Object
show all
Defined in:
lib/guard/ejs.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  run_on_start: true,
  namespace: 'app',
  input: 'public/templates',
  output: 'public/js/templates.js'      
}

Instance Method Summary collapse

Constructor Details

#initialize(watchers = [], options = {}) ⇒ EJS

Returns a new instance of EJS.



15
16
17
18
19
20
21
22
23
24
# File 'lib/guard/ejs.rb', line 15

def initialize(watchers = [], options = {})
  defaults = DEFAULT_OPTIONS.clone
  
  if options[:input]
    defaults.merge!(output: options[:input])
    watchers << ::Guard::Watcher.new(%r{^#{options[:input]}/.+$})
  end
  
  super(watchers, defaults.merge(options))
end

Instance Method Details

#run_allObject

Compile all templates.



34
35
36
# File 'lib/guard/ejs.rb', line 34

def run_all
  run_on_modifications()
end

#run_on_additions(paths) ⇒ Object



43
44
45
# File 'lib/guard/ejs.rb', line 43

def run_on_additions(paths)
  run_all()
end

#run_on_changes(paths) ⇒ Object

Run when the guardfile changes.



39
40
41
# File 'lib/guard/ejs.rb', line 39

def run_on_changes(paths)
  run_all()
end

#run_on_modifications(paths = []) ⇒ Object

Compile each template at the passed in paths.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/guard/ejs.rb', line 48

def run_on_modifications(paths = [])
  hash = {}
  
  # Get all files.
  paths = Dir.glob("#{@options[:input]}/**/*").select do |path|
    not File.directory? path
  end
  
  paths.each do |path|
    file = File.read path
    compiled = ::EJS.compile file
    hash[path] = compiled
    
    UI.info "[Guard::EJS] Compiled #{path}."
  end
  
  # Just overwrite the whole thing for now.
  FileUtils.mkdir_p File.dirname(@options[:output])
  
  File.open(@options[:output], 'w+') do |file|
    file.write "window.#{@options[:namespace]} = window.#{@options[:namespace]} || {}\n"
    file.write "window.#{@options[:namespace]}.templates = {"
    
    hash.each do |name, template|
      file.write "\"#{name}\": #{template},"
    end
    
    file.write "}"
  end
end

#run_on_removals(paths) ⇒ Object



79
80
81
82
# File 'lib/guard/ejs.rb', line 79

def run_on_removals(paths)
  UI.info "Recompiling templates without #{paths}"
  run_all()
end

#startObject



26
27
28
29
30
31
# File 'lib/guard/ejs.rb', line 26

def start
  UI.info 'Guard::EJS is now watching for changes.'
  
  # Run all if the option is true.
  run_all() if @options[:run_on_start]
end