Created
November 17, 2016 04:16
-
-
Save sshaw/752980d4d87d33619be3822d9df75445 to your computer and use it in GitHub Desktop.
Class for rendering ERB templates using "local variable style" in templates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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