Permalink
Browse files

switch to a more sinatra-assetpack inspired api

  • Loading branch information...
1 parent 99a8e6f commit 593fe63413f728d2e312742c0de8ce660ee96423 @gamepoet committed Mar 7, 2012
Showing with 64 additions and 25 deletions.
  1. +64 −25 lib/sinatra/ember.rb
View
@@ -9,36 +9,75 @@ def self.registered(app)
end
module ClassMethods
- # serves ember handlebars templates at the given path
- def serve_templates(path)
- get path do
- content_type :js
-
- # find all the template files
- template_files = {}
- Dir.chdir(settings.views) do
- Dir['**/*.hbs'].map do |filename|
- filename =~ /^(.*)\.hbs$/
- name = $1
- template_files[name] = File.join(settings.views, filename)
+ # set ember options
+ def ember(&block)
+ @ember_options ||= Options.new(self, &block)
+ self.ember_init! if block_given?
+ @ember_options
+ end
+
+ def ember_init!
+ ember.template_packages.each do |route, globs|
+ get route do
+ mtime, output = @template_cache.fetch(route) do
+ # find all the template files
+ paths = globs.map do |glob|
+ glob = File.expand_path(File.join(settings.root, glob))
+ Dir[glob].map { |x| x.squeeze('/') }
+ end
+ paths = paths.flatten.uniq
+
+ # build up template hash
+ template_paths = {}
+ paths.each do |path|
+ template_paths[File.basename(path, '.hbs')] = path
+ end
+
+ # build up the javascript
+ templates = template_paths.map do |(name, path)|
+ content = File.read(path)
+ "Ember.TEMPLATES[#{name.inspect}] = Ember.Handlebars.compile(#{content.inspect});"
+ end
+
+ # wrap it up in a closure
+ output = %{
+ (function() {
+ #{templates.join("\n")}
+ })();
+ }
+ output = output.strip.gsub(/^ {16}/, '')
+
+ # 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, output]
end
- end
- # build up the javascript
- templates = template_files.map do |(name, file)|
- content = File.read(file)
- "Ember.TEMPLATES[#{name.inspect}] = Ember.Handlebars.compile(#{content.inspect});"
+ content_type :js
+ last_modified mtime
+ output
end
-
- # wrap it up in a closure
- output = %{
- (function() {
- #{templates.join("\n")}
- })();
- }
- output.strip.gsub(/^ {12}/, '')
end
end
end
+
+ class Options
+ attr_reader :template_packages
+
+ def initialize(app, &block)
+ @app = app
+ @template_packages = {}
+
+ instance_eval(&block)
+ end
+
+ def templates(route, files=[])
+ @template_packages[route] = files
+ end
+ end
end
end

0 comments on commit 593fe63

Please sign in to comment.