module ErbSandbox

Module contains methods for rendering ERB templates in “sandbox” so code in template will not be able to use your environment (methods, classes, …) It’s useful when you want to encapsulate your program from ERB (e.g. encapsulate models)

Public Class Methods

render(template, variables = {}) click to toggle source

uses ‘erb` (yes-yes, it’s slow:( ) to render template with some predefined variables example:

ErbSandbox.render 'Hello, <%= user %>', user: 'dude' # => "Hello, dude"

@param template [String] @param variables [Hash] @return [String] result of using ‘erb` @raise [ErbSandbox::StatusIsNotZero]

# File lib/erb_sandbox.rb, line 21
def self.render(template, variables = {})
  file = Tempfile.new 'erb_sandbox', encoding: 'UTF-8'
  file.write "<%#-*- coding: UTF-8 -*-%>\n"
  file.write variables_init_code variables
  file.write template
  file.close

  output, status = Open3.capture2e "erb -T 1 #{file.path}" # supress stderr
  file.unlink

  fail(StatusIsNotZero, output) unless status.to_i.zero?
  output
end
render_file(path, variables = {}) click to toggle source

wrapping on ErbSandbox.render(File.read(path), variables) @raise [ErbSandbox::StderrIsNotEmpty] from ErbSandbox.render @raise [Exceptions] from File.read

# File lib/erb_sandbox.rb, line 40
def self.render_file(path, variables = {})
  render File.read(path), variables
end

Private Class Methods

variables_init_code(variables) click to toggle source

generates code, that will define vars with values. @param variables [Hash] var_name => value @return [String] erb code (in <% %>) @raise [TypeError] from Marshal.dump

# File lib/erb_sandbox.rb, line 52
def self.variables_init_code(variables)
  lines = variables.map do |key, value|
    marshal_string = Marshal.dump value
    "#{key} = Marshal.load(#{marshal_string.inspect})" # inspect - like escape string
  end

  "<%\n#{lines.join "\n"}\n%>"
end