Skip to content

Instantly share code, notes, and snippets.

@sshaw
Created November 17, 2016 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sshaw/752980d4d87d33619be3822d9df75445 to your computer and use it in GitHub Desktop.
Save sshaw/752980d4d87d33619be3822d9df75445 to your computer and use it in GitHub Desktop.
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