Skip to content

Instantly share code, notes, and snippets.

@sshaw sshaw/template.rb
Created Nov 17, 2016

Embed
What would you like to do?
Class for rendering ERB templates using "local variable style" in templates
require "erb"
class Template
def initialize(template)
@__template = ::ERB.new(template, nil, "-")
end
def render(__vars = {})
__b = binding
__names = []
__vars.each do |k, v|
__names << k.to_s.gsub(/[^\w]+/, "_")
# Only >= 2.1
__b.local_variable_set(__names.last, v)
end
@__template.result(__b)
ensure
__names.each { |name| __b.local_variable_set(name, nil) }
end
end
if $0 == __FILE__
t = Template.new("Oizinho <%= name %>!")
puts t.render :name => "sshaw"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.