Sha256: 9dbb1080489131b7fc95136bec050fe9d8c3667644fa72660da188486cc92fb5

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 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
    
    protected
    
    def coffee_options
      "-p"
    end
    
    def temp_file_for_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

1 entries across 1 versions & 1 rubygems

Version Path
barista-0.1.2 lib/barista/compiler.rb