Skip to content

Instantly share code, notes, and snippets.

@stevenharman
Last active December 16, 2020 17:28

Revisions

  1. stevenharman revised this gist Dec 16, 2020. No changes.
  2. stevenharman created this gist Dec 16, 2020.
    30 changes: 30 additions & 0 deletions erb_now.rb
    Original 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