Sha256: 27410fa55cb9872bc603235478d95085f68e62de81dd2d3e6160d6ba51a8e548

Contents?: true

Size: 1.57 KB

Versions: 4

Compression:

Stored size: 1.57 KB

Contents

require 'active_support'
require 'action_view'
require 'curly'

class Curly::TemplateHandler

  # Handles a Curly template, compiling it to Ruby code. The code will be
  # evaluated in the context of an ActionView::Base instance, having access
  # to a number of variables.
  #
  # template - The ActionView::Template template that should be compiled.
  #
  # Returns a String containing the Ruby code representing the template.
  def self.call(template)
    path = template.virtual_path
    presenter_class = Curly::Presenter.presenter_name_for_path(path)

    source = Curly.compile(template.source)
    template_digest = Digest::MD5.hexdigest(template.source)

    # Template is empty, so there's no need to initialize a presenter.
    return %("") if template.source.empty?

    <<-RUBY
    if local_assigns.empty?
      options = assigns
    else
      options = local_assigns
    end

    presenter = #{presenter_class}.new(self, options.with_indifferent_access)

    view_function = lambda do
      #{source}
    end

    if key = presenter.cache_key
      @output_buffer = ActiveSupport::SafeBuffer.new

      template_digest = #{template_digest.inspect}

      if #{presenter_class}.respond_to?(:cache_key)
        presenter_key = #{presenter_class}.cache_key
      else
        presenter_key = nil
      end

      options = {
        expires_in: presenter.cache_duration
      }

      cache([template_digest, key, presenter_key].compact, options) do
        safe_concat(view_function.call)
      end

      @output_buffer
    else
      view_function.call.html_safe
    end
    RUBY
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
curly-templates-0.5.0 lib/curly/template_handler.rb
curly-templates-0.4.0 lib/curly/template_handler.rb
curly-templates-0.3.1 lib/curly/template_handler.rb
curly-templates-0.3.0 lib/curly/template_handler.rb