Last active
December 16, 2020 17:28
Revisions
-
stevenharman revised this gist
Dec 16, 2020 . No changes.There are no files selected for viewing
-
stevenharman created this gist
Dec 16, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,30 @@ require "ostruct" # A wrapper around a single ERB template that will bind the given Hash of values, # making them available as local variables w/in the template. class ErbNow < OpenStruct # Render a given ERB +template+ string, binding the entries in the given +attrs+ Hash # as local variables in the template, with the key as the variable name. # # @example # # template = <<~ERB # <h1>Hello, <%= name %>!</h1> # <p>The current time is: <time datetime="<%= timestamp %>"><%= timestamp.strftime("%d of %B, %Y")%></time>.</p> # ERB # # ErbNow.render(template, name: "Alice", timestamp: Time.now) # # => <h1>Hello, Alice</h1> # => <p>The current time is: <time datetime="2020-12-16 10:31:36 -0500">16 of December, 2020</time>.</p> # # @param [String] template An ERB template, as a String. # @param [Hash] attrs A Hash of values to be bound to the template, with the key as the local name. def self.render(template, attrs = {}) new(attrs).render(template) end def render(template) ERB.new(template).result(binding) end end