Class: Guard::Handlebars

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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Handlebars.



8
9
10
11
12
13
# File 'lib/guard/handlebars.rb', line 8

def initialize(watchers = [], options = {})
  @options = {
    :notifications => true
  }.merge(options)
  super(watchers, @options)
end

Instance Method Details

#compile_handlebars(file) ⇒ Object



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

def compile_handlebars file
  content = File.new(file).read
  begin
    com = "handlebars #{file}"
    result = `#{com}`
    result
  rescue StandardError => error
    puts "ERROR COMPILING #{file}"
  end
end

#get_output(file) ⇒ String

Get the file path to output the js based on the file being built. The output path is relative to where guard is being run.

Parameters:

  • file (String)

    path to file being built

Returns:

  • (String)

    path to file where output should be written



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

def get_output(file)
  file_dir = File.dirname(file)
  file_name = File.basename(file).split('.')[0..-2].join('.')
  unless file_name =~ /\.js$/
    file_name << ".js"
  end
  
  file_dir = file_dir.gsub(Regexp.new("#{@options[:input]}(\/){0,1}"), '') if @options[:input]
  file_dir = File.join(@options[:output], file_dir) if @options[:output]

  if file_dir == ''
    file_name
  else
    File.join(file_dir, file_name)
  end
end

#notify(changed_files) ⇒ Object



64
65
66
67
68
69
# File 'lib/guard/handlebars.rb', line 64

def notify(changed_files)
  ::Guard.guards.reject{ |guard| guard == self }.each do |guard|
    paths = Watcher.match_files(guard, changed_files)
    guard.run_on_change paths unless paths.empty?
  end
end

#run_allObject



49
50
51
# File 'lib/guard/handlebars.rb', line 49

def run_all
  run_on_change(Watcher.match_files(self, Dir.glob(File.join('**', '*.*'))))
end

#run_on_change(paths) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/guard/handlebars.rb', line 53

def run_on_change(paths)
  paths.each do |file|
    output_file = get_output(file)
    FileUtils.mkdir_p File.dirname(output_file)
    File.open(output_file, 'w') { |f| f.write(compile_handlebars(file)) }
    ::Guard::UI.info "# compiled handlebars in '#{file}' to js in '#{output_file}'"
    ::Guard::Notifier.notify("# compiled handlebars in #{file}", :title => "Guard::Handlebars", :image => :success) if @options[:notifications]
  end
  notify paths
end