Module: Sinatra::Handlebars::ClassMethods

Defined in:
lib/sinatra/handlebars.rb

Instance Method Summary collapse

Instance Method Details

#handlebars(&block) ⇒ Object

set handlebars options



16
17
18
19
20
# File 'lib/sinatra/handlebars.rb', line 16

def handlebars(&block)
  @handlebars_options ||= Options.new(self, &block)
  handlebars_init! if block_given?
  @handlebars_options
end

#handlebars_init!Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/sinatra/handlebars.rb', line 22

def handlebars_init!
  handlebars.template_packages.each do |route, globs|
    get route do
      mtime, output = @template_cache.fetch(route) do

        paths = globs.map do |glob|
          glob = File.expand_path(glob)
          Dir[glob].map { |x| x.squeeze('/') }
        end.flatten.uniq

        # compute the maximum mtime for all paths
        mtime = paths.map do |path|
          if File.file?(path)
            File.mtime(path).to_i
          end
        end.compact.max

        [mtime, self.class.js_content(paths)]
      end

      content_type :js
      last_modified mtime
      output
    end
  end
end

#js_content(paths) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/sinatra/handlebars.rb', line 57

def js_content(paths)
  @js_content ||= %{
    // Vendor Content
    #{vendor_js}
    
    //Templates
    (function() {
      window.HandlebarsTemplates = {};
      #{templates_as_javascript(paths).join("\n")}
    })();
  }.strip.gsub(/^ {16}/, '')
end

#template_paths(paths) ⇒ Object



81
82
83
84
85
86
87
# File 'lib/sinatra/handlebars.rb', line 81

def template_paths(paths)
  template_paths = {}
  paths.each do |path|
    template_paths[File.basename(path, '.hbs')] = path
  end
  template_paths
end

#templates_as_javascript(paths) ⇒ Object



70
71
72
73
74
75
76
77
78
79
# File 'lib/sinatra/handlebars.rb', line 70

def templates_as_javascript(paths)
  template_paths(paths).map do |(name, path)|
    content = File.read(path)
    if name =~ /^_/
      "Handlebars.registerPartial(#{name.sub(/^_/, '').inspect}, #{content.inspect});"
    else
      "window.HandlebarsTemplates[#{name.inspect}] = Handlebars.compile(#{content.inspect});"
    end
  end
end

#vendor_jsObject



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

def vendor_js
  vendor_js_files.inject('') {|memo, path| memo + File.read(path) }
end

#vendor_js_filesObject



53
54
55
# File 'lib/sinatra/handlebars.rb', line 53

def vendor_js_files
  Dir[File.join(File.dirname(__FILE__), '../../', 'vendor', '/*.js')]
end