Class: Guard::Jst

Inherits:
Plugin
  • Object
show all
Defined in:
lib/guard/jst.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Jst

Returns a new instance of Jst.



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

def initialize(options = {})
  super
  @options = { extnames: %w[jst ejs jst.ejs] }.merge options

  @output = Pathname.new @options[:output]
  @input  = Pathname.new @options[:input]
end

Instance Method Details

#run_allObject

Compile all templates.



22
23
24
25
# File 'lib/guard/jst.rb', line 22

def run_all
  paths = Dir.glob("#{@options[:input]}/**/*#{extnames}").select { |path| not File.directory? path }
  run_on_modifications paths
end

#run_on_additions(paths) ⇒ Object



32
33
34
# File 'lib/guard/jst.rb', line 32

def run_on_additions(paths)
  run_on_modifications paths
end

#run_on_changes(paths) ⇒ Object

Run when the guardfile changes.



28
29
30
# File 'lib/guard/jst.rb', line 28

def run_on_changes(paths)
  run_on_modifications paths
end

#run_on_modifications(paths = []) ⇒ Object

Compile each template at the passed in paths.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/guard/jst.rb', line 37

def run_on_modifications(paths = [])
  paths
    .select { |path| @options[:extnames].include? path.scan(/\.(.+)/).flatten[0] }
    .map { |path| Pathname path }
    .uniq.each do |path|
      relative_path = path.relative_path_from @input

      UI.info "[JST] COMPILE: #{path}"

      File.open(@output.join(relative_path).tap { |target| target.dirname.mkpath }.to_s.sub(/\..+/, '.js'), 'w+') do |file|
        file.write <<-JS
(function() {
  this.JST || (this.JST = {});
  this.JST["#{relative_path.to_s.sub(/\..+/, '')}"] = #{EJS.compile path.read}
}).call(this)
      JS
      end
    end
end

#run_on_removals(paths) ⇒ Object



57
58
59
60
61
62
# File 'lib/guard/jst.rb', line 57

def run_on_removals(paths)
  paths.each do |path|
    UI.info "[JST] REMOVE: #{path}"
    File.delete @output.join(Pathname.new(path).relative_path_from(@input)).to_s.sub(/\..+/, '.js')
  end
end

#startObject



15
16
17
18
19
# File 'lib/guard/jst.rb', line 15

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