Sha256: c35c4e65d1afa1ba484261a89693bca024f47619a4f9b04648094a2a66aa65af

Contents?: true

Size: 1.29 KB

Versions: 2

Compression:

Stored size: 1.29 KB

Contents

require 'digest/sha2'

module Barista
  class Compiler
    
    class << self; attr_accessor :bin_path; end
    self.bin_path ||= "coffee"
    
    def self.compile(content)
      new(content).to_js
    end
    
    def initialize(content)
      @compiled = false
      @content  = content
    end
    
    def compile!
      # Compiler code thanks to bistro_car.
      tf = temp_file_for_content
      @compiled_content = invoke_coffee(temp_file_for_content.path)
      @compiled = true
    ensure
      tf.unlink rescue nil
    end
    
    def to_js
      compile! unless @compiled
      @compiled_content.to_s
    end
    
    def self.dirty?(from, to)
      File.exist?(from) && (!File.exist?(to) || File.mtime(to) < File.mtime(from))
    end
    
    protected
    
    def coffee_options
      ["-p"].tap do |options|
        options << "--no-wrap" if Barista.no_wrap?
      end.join(" ")
    end
    
    def temp_file_for_content(content = @content)
      tf = Tempfile.new("barista-#{content_hash}.coffee")
      tf.write content
      tf.close
      tf
    end
    
    def invoke_coffee(path)
      command = "#{self.class.bin_path} #{coffee_options} '#{path}'".squeeze(' ')
      %x(#{command})
    end
    
    def content_hash
      @content_hash ||= Digest::SHA256.hexdigest(@content)
    end
    
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
barista-0.2.1 lib/barista/compiler.rb
barista-0.2.0 lib/barista/compiler.rb