Sha256: 9936682c109488e0b3c61383d4a61d45292f9c260143699253d6803fd50c6820

Contents?: true

Size: 1.6 KB

Versions: 1

Compression:

Stored size: 1.6 KB

Contents

require 'tilt'

module HandlebarsAssets
  class TiltHandlebars < Tilt::Template
    def self.default_mime_type
      'application/javascript'
    end

    def evaluate(scope, locals, &block)
      template_path = TemplatePath.new(scope)

      compiled_hbs = Handlebars.precompile(data, HandlebarsAssets::Config.options)

      if template_path.is_partial?
        <<-PARTIAL
          (function() {
            Handlebars.registerPartial(#{template_path.name}, Handlebars.template(#{compiled_hbs}));
          }).call(this);
        PARTIAL
      else
        <<-TEMPLATE
          (function() {
            this.HandlebarsTemplates || (this.HandlebarsTemplates = {});
            this.HandlebarsTemplates[#{template_path.name}] = Handlebars.template(#{compiled_hbs});
            return HandlebarsTemplates[#{template_path.name}];
          }).call(this);
        TEMPLATE
      end
    end

    protected

    def prepare; end


    class TemplatePath
      def initialize(scope)
        self.template_path = scope.logical_path
      end

      def is_partial?
        template_path.gsub(%r{.*/}, '').start_with?('_')
      end

      def name
        is_partial? ? partial_name : template_name
      end

      private

      attr_accessor :template_path

      def forced_underscore_name
        '_' + relative_path
      end

      def relative_path
        template_path.gsub(/^#{HandlebarsAssets::Config.path_prefix}\/(.*)$/i, "\\1")
      end

      def partial_name
        forced_underscore_name.gsub(/\//, '_').gsub(/__/, '_').dump
      end

      def template_name
        relative_path.dump
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
handlebars_assets-0.6.2 lib/handlebars_assets/tilt_handlebars.rb