Module: Sinatra::Ember::ClassMethods

Defined in:
lib/sinatra/ember.rb

Instance Method Summary collapse

Instance Method Details

#ember(&block) ⇒ Object

set ember options



13
14
15
16
17
# File 'lib/sinatra/ember.rb', line 13

def ember(&block)
  @ember_options ||= Options.new(self, &block)
  self.ember_init! if block_given?
  @ember_options
end

#ember_init!Object



19
20
21
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/sinatra/ember.rb', line 19

def ember_init!
  ember.template_packages.each do |route, spec|
    get route do
      mtime, output = @template_cache.fetch(route) do
        # find all the template files
        paths = spec.globs.map do |glob|
          glob = File.expand_path(File.join(settings.root, glob))
          Dir[glob].map { |x| x.squeeze('/') }
        end

        # define the portion of the path to remove
        remove = settings.root
        if spec.opts[:relative_to].empty?
          remove = settings.root
        else
          remove = File.join(remove, spec.opts[:relative_to])
        end
        remove = File.expand_path(remove)

        # build up the javascript
        templates = paths.map do |files|
          files.map do |file|
            # derive the template name
            tmpl_name = file.sub(/\.(handlebars|hbs|hjs)$/, '')
            if settings.ember.template_name_style == :path
              tmpl_name.sub!(/^#{Regexp.quote(remove)}\//, '')
            else
              tmpl_name = File.basename(tmpl_name)
            end

            # add the template content
            content = File.read(file)
            "Ember.TEMPLATES[#{tmpl_name.inspect}] = Ember.Handlebars.compile(#{content.inspect});"
          end
        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.flatten.map do |path|
          if File.file?(path)
            File.mtime(path).to_i
          end
        end.compact.max

        [mtime, output]
      end

      content_type :js
      last_modified mtime
      output
    end
  end
end