Sha256: 256a54310d16630ced0df64d2043ede6dec22a4e8b4f91532f80df8cff27d583

Contents?: true

Size: 1.37 KB

Versions: 5

Compression:

Stored size: 1.37 KB

Contents

require "tilt"

class Tynn
  module Render
    def self.setup(app, options = {}) # :nodoc:
      app.settings.update(
        layout: options.fetch(:layout, "layout"),
        views: options.fetch(:views, File.expand_path("views", Dir.pwd)),
        engine: options.fetch(:engine, "erb"),
        engine_opts: {
          escape_html: true
        }.merge!(options.fetch(:options, {}))
      )
    end

    module InstanceMethods
      def render(template, locals = {}, layout = self.class.settings[:layout])
        res.headers[Rack::CONTENT_TYPE] ||= Syro::Response::DEFAULT

        res.write(view(template, locals, layout))
      end

      def view(template, locals = {}, layout = self.class.settings[:layout])
        return partial(layout, locals.merge(content: partial(template, locals)))
      end

      def partial(template, locals = {})
        return tilt(template_path(template), locals, self.class.settings[:engine_opts])
      end

      private

      def tilt(file, locals = {}, opts = {})
        return tilt_cache.fetch(file) { Tilt.new(file, 1, opts) }.render(self, locals)
      end

      def tilt_cache
        return Thread.current[:tilt_cache] ||= Tilt::Cache.new
      end

      def template_path(template)
        dir = self.class.settings[:views]
        ext = self.class.settings[:engine]

        return File.join(dir, "#{ template }.#{ ext }")
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
tynn-1.4.0 lib/tynn/render.rb
tynn-1.3.0 lib/tynn/render.rb
tynn-1.2.0 lib/tynn/render.rb
tynn-1.1.0 lib/tynn/render.rb
tynn-1.0.0 lib/tynn/render.rb