Skip to content

Instantly share code, notes, and snippets.

@christiankakesa
Last active March 12, 2017 22:18
Show Gist options
  • Save christiankakesa/0cac871a1cb73f2b43a92561848635d1 to your computer and use it in GitHub Desktop.
Save christiankakesa/0cac871a1cb73f2b43a92561848635d1 to your computer and use it in GitHub Desktop.
Erubi template engine test
# frozen_string_literal: true
require 'erubi'
require 'shield'
class ErubiDeck < Syro::Deck
include Shield::Helpers
LAYOUT = 'layout'
VIEW = 'views/%s.erb'
DEFAULT_OPTIONS = {
preamble: false,
postamble: false,
ensure: true
}.freeze
def session
req.session
end
def partial(template, vars = {}, context = self)
filename_path = view_path(template)
opts = { filename: filename_path }
erubi_cache[template] ||= read_template(filename_path)
build_dynamic_methods(vars, context, filename_path)
eval(Erubi::Engine.new(erubi_cache[template], DEFAULT_OPTIONS.merge(opts))
.src)
end
def render(template, vars = {})
res.html partial(LAYOUT, content: partial(template, vars))
end
def either(*segments)
default { yield } if segments.any? { |segment| consume(segment) }
end
private
def view_path(template)
format(VIEW, template)
end
def read_template(file)
data = File.open(file, 'rb', &:read)
data&.force_encoding(Encoding.default_external) if Encoding.default_external
data
end
def build_dynamic_methods(vars, context, filename)
return if vars.empty?
vars[:title] = nil unless vars.include?(:title)
Thread.current[:_erubi_deck_vars] = vars
code = String.new
vars.keys.each do |key|
code << format("def %s; Thread.current[:_erubi_deck_vars][%p]; end\n",
key,
key)
end
context.instance_eval(code, filename, -1)
end
def erubi_cache
Thread.current[:_erubi_deck_cache] ||= {}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment