Skip to content

Instantly share code, notes, and snippets.

@gjvis
Created April 1, 2015 17:55
Show Gist options
  • Save gjvis/cda554a8a10aaade0022 to your computer and use it in GitHub Desktop.
Save gjvis/cda554a8a10aaade0022 to your computer and use it in GitHub Desktop.
Render an ERB with an instance as the context
require 'erb'
class Context
attr_accessor :foo
attr_accessor :bar
def initialize(foo:, bar:)
self.foo = foo
self.bar = bar
end
def get_binding
# as of 1.9.2 Kernel.binding returns the binding of the callsite, so we
# have to actually call binding from within the instance
binding
end
end
context = Context.new(foo: 'hello', bar: 'world')
puts context.inspect
template = <<EOS
foo is "<%= foo %>", and bar is "<%= bar %>"
EOS
erb = ERB.new(template)
puts erb.result(context.get_binding)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment